Search code examples
rmedian

Rolling median in R


I need to calculate rolling median. And have following code

i <- 0
median_roll<-c("")
x<-c(1:10)
n<-2
y<-as.data.frame(x)
  while(i < length(x)-n){
    median_roll[i] <- median(y[i:i+n,])
    i <- i + 1  
  }

Which produce following reluts in median_roll

[1] "3" "4" "5" "6" "7" "8" "9"

What i need is

[1] "2" "3" "4" "5" "6" "7" "8" "9"

Solution

  • Here are three options.
    First the data.

    x <- 1:10
    y <- data.frame(x)
    n <- 2L
    

    1 Base R, for loop.

    median_roll <- numeric(length(x) - n)
    for(i in seq_along(median_roll)){
      median_roll[i] <- median(y[i:(i+n), ])
    }
    
    median_roll
    #[1] 2 3 4 5 6 7 8 9
    

    2 Base R, sapply loop.

    sapply(seq_along(median_roll), \(i, n) median(y[i:(i+n), ]), n = 2L)
    #[1] 2 3 4 5 6 7 8 9
    

    3 Package zoo.

    zoo::rollapplyr(y$x, width = 3L, FUN = median)
    #[1] 2 3 4 5 6 7 8 9