s-news
[Top] [All Lists]

Re: moving median in S without looping (2)

To: "Loecher, Markus" <Markus.Loecher@scr.siemens.com>
Subject: Re: moving median in S without looping (2)
From: John Fox <jfox@mcmaster.ca>
Date: Tue, 21 Jan 2003 10:44:23 -0500
Cc: "Gunter, Bert" <bert_gunter@merck.com>, "'s-news@wubios.wustl.edu'" <s-news@wubios.wustl.edu>
Dear Markus,

I noticed that the "solution" that I sent previously loses the first value of the result; here's a corrected version:

    running.median <- function(x, lag){
        n <- length(x)
        X <- matrix(x, n, lag)
        for (i in 2:lag) X[1:(n-i+1), i] <- x[-(1:(i-1))]
        apply(X, 1, median)[1:(n-lag+1)]
        }

As well, Bert Gunter pointed out to me that the use of apply makes this function slow, and sent a much cleverer and faster solution, providing an example for running medians of span 3 (due originally to Bill Venables). This generalizes as follows, for odd span:

    running.median <- function(x, lag){
        mid <- ceiling(lag/2)
        if (lag == mid*2) stop("lag must be odd")
        n <- length(x)
        X <- matrix(x, n, lag)
        for (i in 2:lag) X[1:(n-i+1), i] <- x[-(1:(i-1))]
        X <- X[1:(n-lag+1),]
        index<-rep(lag:n, lag)
        X <- X[order(index,X)]
        X[seq(mid, lag*(n-lag+1) - mid + 1, by=lag)]
        }

(It shouldn't be too hard to provide medians for even spans as well, but I've already gotten myself into enough trouble this morning.)

Maybe this will be of more use.
  John

-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox@mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------


<Prev in Thread] Current Thread [Next in Thread>
  • Re: moving median in S without looping (2), John Fox <=