Moving Average with a variable time window in R

I want to calculate a moving average for a specific time window without generating NA at the beginning of the time series. For example, if I set the time window to 3, in the first two observations there will be NS. I want to have a time window of 1 for the first observation, 2 for the second observation, and then 3 for all other observations.

My current code is:

#example data
x <- c(3,9,2,8,4,6,5,8)
#moving average with time window of length 3
(ma3 <- filter(x,rep(1/3,3),sides=1))
+6
source share
6 answers

I see no other way than brute force:

Using rollapplyfrom a package zooinstead filter:

c(x[1], mean(x[1:2]), rollapply(x, width=3, FUN=mean))
+5
source

Let me jump onto the train rollapplytoo:

> rollapply(c(NA, NA, x), width=3, FUN=mean, na.rm=T)
[1] 3.000000 6.000000 4.666667 6.333333 4.666667 6.000000 5.000000 6.333333

= 3-1 NA na.rm=T , . ,

> rollapply(c(NA, NA, x), width=3, FUN=function(v) mean(v, na.rm=T))

.

+3

@thelatemail , (test[] x[] ), , ( = 2). + 1 i- ( n- ). , :

movavg.grow = function(x,window) {
  startma = sapply(1:(floor(window/2)),function(y) mean(x[1:((y-1)*2+1)]))
  endma = sapply(1:(floor(window/2)),function(y) mean(x[(length(x)-((y-1)*2)):length(x)]))
  endma = rev(endma)
  c(startma,
    filter(x,rep(1/window,window))[(floor(window/2):(length(x)- floor(window)/2)+1)],
    endma)
}

, 1:10 x=1:10

> x=1:10
> x
 [1]  1  2  3  4  5  6  7  8  9 10
> movavg.grow(x,5)
 [1]  1  2  3  4  5  6  7  8  9 10
> movavg.grow(x,3)
 [1]  1  2  3  4  5  6  7  8  9 10
+2

. .

+1

R, :

movavg.grow <- function(x,window,sides) {
 startma <- sapply(1:(window-1),function(y) mean(x[1:y]))
 c(startma,filter(x,rep(1/window,window),sides=sides)[window:length(x)])
}

:

> test <- c(3,9,2,8,4,6,5,8)
> movavg.grow(x=test,window=3,sides=1)
[1] 3.000000 6.000000 4.666667 6.333333 4.666667 6.000000 5.000000 6.333333
+1

, , "" , AFAIK .

data.table , 1.12.0.
, , , "" :

x = c(3,9,2,8,4,6,5,8)
window = 3

library(data.table)
n = c(seq.int(window), rep(window, length(x)-window))
frollmean(x, n, adaptive=TRUE)
#[1] 3.000000 6.000000 4.666667 6.333333 4.666667 6.000000 5.000000 6.333333

?froll.

0

All Articles