Home > Software engineering >  Rolling median in R
Rolling median in R

Time:10-10

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"

CodePudding user response:

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

CodePudding user response:

In R, indexing starts with 1 with which i should initialized accordingly.

i <- 1; x <- 1:10; r <- NULL; n <- 2
while (i - 1   n < length(x)) {
  r[i] <- median(x[i:(i   n)])
  i <- i   1
}
r
# [1] 2 3 4 5 6 7 8 9

You can also use a repeat loop which might be more readable.

i <- 1; x <- 1:10; r <- NULL; n <- 2
repeat {
  r[i] <- median(x[i:(i   n)])
  i <- i   1
  if (i - 1   n == length(x))
    break
}
r
# [1] 2 3 4 5 6 7 8 9

An sapply(Map()) solution.

x <- 1:10; n <- 2
sapply(Map(` `, list(1:(n   1L)), seq(0, length(x) - n - 1L, n - 1L)), 
       \(s) median(x[s]))
# [1] 2 3 4 5 6 7 8 9
  • Related