Find on average the last 4 items

My dataset looks like this:

df<- data.frame(c("a", "a", "a", "a", "a", "a", "a", "a", "b", "b", "b", "b", "b", "b", "b", "b"),
                c(1,    1,   1,   1,   2,   2,   2,   2,   1,   1,    1,  1,   2,    2,   2,   2),
                c(1,    2,   3,   4,   1,   2,   3,   4,   1,   2,   3 , 4,  1,    2,   3,   4),
                c(25,   75,  20,  40,  60,  50,  20,  10,  20,  30,  40,  60, 25,   75,  20,  40))
colnames(df)<-c("car", "year", "mnth", "val")

      

For clarity, I'll show it here as well:

   car year mnth val
1    a    1    1  25
2    a    1    2  75
3    a    1    3  20
4    a    1    4  40
5    a    2    1  60
6    a    2    2  50
7    a    2    3  20
8    a    2    4  10
9    b    1    1  20
10   b    1    2  30
11   b    1    3  40
12   b    1    4  60
13   b    2    1  25
14   b    2    2  75
15   b    2    3  20
16   b    2    4  40

      

I would like to add a new column tmp

in df

, where for a particular row, the value tmp

should be the average df$val

and 3 preceding values. Below are examplestmp

#row 3: mean(25,75,20)=40
#row 4: mean(25,75,20,40)=40
#row 5: mean(75,20,40,60)=48.75
#row 16: mean(25,75,20,40)=40

      

Is there an efficient way to do this in R without using for

-loops?

+1


source to share


4 answers


For each value, calculate the mean of the rolling window that includes the value as well as the preceding 3 values ​​(index i-3

to index i

in the solution below). For cases where i-3

negative, you can simply use 0

( max((i-3),0)

)

sapply(seq_along(df$val), function(i)
      mean(df$val[max((i-3),0):i], na.rm = TRUE))
#[1] 25.00 50.00 40.00 40.00 48.75 42.50 42.50 35.00 25.00
#[10] 20.00 25.00 37.50 38.75 50.00 45.00 40.00

      



Also consider rollmean

ofzoo

library(zoo)
c(rep(NA,3), rollmean(x = df$val, k = 4))
#[1]    NA    NA    NA 40.00 48.75 42.50 42.50 35.00 25.00 20.00 25.00
#[12] 37.50 38.75 50.00 45.00 40.00
#FURTHER TWEAKING MAY BE NECESSARY

      

+1


source


Here's a (somewhat) vectorized solution using data.table::shift

library(data.table)
colMeans(do.call(rbind, shift(df$val, 0:3)), na.rm = TRUE)
## [1] 25.00 50.00 40.00 40.00 48.75 42.50 42.50 35.00 25.00 20.00 25.00 37.50 38.75 50.00 45.00 40.00

      




Or as @Frank suggested

rowMeans(setDF(shift(df$val, 0:3)), na.rm = TRUE)

      

+4


source


Or just like that

library(dplyr)
df$tmp <- (df$val+lag(df$val,1)+lag(df$val,2)+lag(df$val,3))/4

      

It doesn't use any loop. It just shifts the list and adds up the shifted lists.

For example, if you define

a <- c(1,2,3,4,5)

      

then

lag(a) 

      

is an

NA  1  2  3  4

      

I hope this can help you.

+2


source


You can also use data.table

library(data.table)

setDT(df)
df[, tmp := (val + shift(val,1,type="lag") + shift(val,2,type="lag") + shift(val,3,type="lag"))/4]

      

+1


source







All Articles