Roll and feeder at the beginning of the data series

I want to make a moving average from the previous 4 values ​​in a dataset. However, for starters, since there are no 4 values, I want to make an average value for 1/2/3 of the observations. How to do it?

library(zoo) df= data.frame(a=c(1,2,3,4,5)) df$answer = rollapply(df$a, 4,mean) #help 

For example, line 1 will have the value 1, line 2 will have the value (1 + 2) / 2 = 1.5, line 3 will have the value 6/3 = 2.

I want to cast from 4 periods, but in periods with fewer months I want to make the average of the allowable maximum periods.

+6
source share
4 answers

Use the correct setting with partial=TRUE , i.e. rollapplyr(..., partial=TRUE) or rollapply(..., align = "right", partial=TRUE ). Here we use rollapplyr :

 rollapplyr(df$a, 4, mean, partial = TRUE) 
+7
source

I think this can simply be done with a simple function such as the following (as an alternative solution):

 rollapply2 <- function(myvec, width, fun){ #the first values up to width firstvalues <- cumsum(myvec[1:(width-1)])/(1:(width-1)) #the rest of the values as normal normalvalues <- rollapply(myvec, width, fun) #return them all c(firstvalues,normalvalues) } 

Output:

 > rollapply2(df$a, 4, mean) [1] 1.0 1.5 2.0 2.5 3.5 
+3
source

You can also try without a package:

 sapply(seq_along(df$a), function(u) mean(df$a[max(u-3,0):u])) #[1] 1.0 1.5 2.0 2.5 3.5 

Or a vectorized solution - no loop - R base:

 with(df, (cumsum(a) - c(rep(0,4),head(a,-4)))/pmin(seq_along(a),4)) #[1] 1.0 1.5 2.0 2.5 3.5 
+2
source

How about adding extra NA?

 rollapply(c(rep(NA, 3),df$a), 4, FUN = mean, align = "right", na.rm = TRUE) 
+1
source

Source: https://habr.com/ru/post/984915/


All Articles