Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rolling average by group R data.table

Tags:

r

data.table

I want to compute a YTD rolling average by group starting from the first row in the group and ending at the last row. Sample below...

Group <- c(rep("a",5), rep("b",5))
Sales <- c(2,4,3,3,5,9,7,8,10,11)
Result <- c(2,3,3,3,3.4,9,8,8,8.5,9)
df <- data.frame(Group, Sales, Result)

The Result column is what I am expecting to see from the rolling average.

like image 332
MidnightDataGeek Avatar asked Jun 23 '16 08:06

MidnightDataGeek


2 Answers

Using cumsum:

dt <- as.data.table(df)
dt[, res := cumsum(Sales)/(1:.N), by = Group]
dt
    Group Sales Result res
 1:     a     2    2.0 2.0
 2:     a     4    3.0 3.0
 3:     a     3    3.0 3.0
 4:     a     3    3.0 3.0
 5:     a     5    3.4 3.4
 6:     b     9    9.0 9.0
 7:     b     7    8.0 8.0
 8:     b     8    8.0 8.0
 9:     b    10    8.5 8.5
10:     b    11    9.0 9.0

or with rollapplyr from the zoo package:

dt[, res := rollapplyr(Sales, 1:.N, mean), by = Group]

or with base R:

ave(df$Sales, df$Group, FUN = function(x) cumsum(x) / seq_along(x))
like image 69
nachti Avatar answered Oct 11 '22 01:10

nachti


We can use dplyr with zoo. The %>% connects the lhs with the rhs and it is very easy to understand and execute it.

library(dplyr)
library(zoo)
df %>%
   group_by(Group) %>% 
   mutate(Sales = rollapplyr(Sales, row_number(), mean))  
#    Group Sales Result
#    <fctr> <dbl>  <dbl>
#1       a   2.0    2.0
#2       a   3.0    3.0
#3       a   3.0    3.0
#4       a   3.0    3.0
#5       a   3.4    3.4
#6       b   9.0    9.0
#7       b   8.0    8.0
#8       b   8.0    8.0
#9       b   8.5    8.5
#10      b   9.0    9.0
like image 2
akrun Avatar answered Oct 11 '22 02:10

akrun