Arian Modarres
Arian Modarres

Reputation: 27

How to calculate rolling mean for multiple columns at once with a groupby and select in dplyr, while ignoring the groupby columns

I am trying to get rolling means for many columns at once, but I am running into difficulty because my grouping variables are not numeric.

If I were to do a rolling mean for one column at a time, my code should look something like this :

NHLReg2<-arrange(NHLReg2,season,team,gameId) %>% group_by(season,team)%>% mutate(xGF= rollapply(xGoalsFor, list( seq(21)), sum, partial = TRUE, fill = NA))

I have attempted to use dplyr in order to do many columns at the same time:

NHLPP3<-arrange(NHLPP2,season,team,gameId) %>%
group_by(season,team)%>%
select(c(1,2,11:112)) %>%
lapply(function(x){ if(class(x) == "numeric"){
rollapply(x, width=list(-seq(21)), FUN=function(x){sum(x,
na.rm=T)},partial = T, fill = NA)
}else{
return(x)
}
})%>% as.data.frame()

This does solve the problem of ignoring the character/grouping variables for the rollapply, but it causes the groupby statement to have no effect. I have left some sample data below, pretend v1 and v2 are the grouping variables and v3 and v4 are the columns of interest to calculate a rolling mean.

v1<-c('a','a','a','a','a','a','a','a','b','b','b','b','b','b','b')
v2<-c('2010','2010','2010','2010','2010','2010','2010','2010','2020','2020','2020','2020','2020','2020','2020')
v3<-c(1,2,3,4,1,4,5,6,13,5,6,13,4,65,8)
v4<-c(6,13,5,6,13,4,65,8,1,2,3,4,1,4,5)
Data<-as.data.frame(t(rbind(v1,v2,v3,v4)))

Thank you.

Upvotes: 0

Views: 1087

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269654

Data, as defined in the question, has no numeric columns. It is all factors. We fix the definition below. Then we use mutate_at to just apply rollapplyr to the non-grouping columns. So that we can use Data, we roll the sum over the prior 3 values rather than the prior 21. An alternative to the mutate_at line would be mutate_if(is.numeric, ~ rollapplyr(...same...)) .

library(dplyr)
library(zoo)

Data <- data.frame(v1, v2, v3, v4) # v1, v2, v3, v4 are from question  

Data %>%
  group_by(v1, v2) %>%
  mutate_at(vars(-group_cols()), 
    ~ rollapplyr(.x, list(-seq(3)), sum, na.rm = FALSE, partial = TRUE, fill = NA)) %>%
  ungroup

giving:

# A tibble: 15 x 4
   v1    v2       v3    v4
   <fct> <fct> <dbl> <dbl>
 1 a     2010     NA    NA
 2 a     2010      1     6
 3 a     2010      3    19
 4 a     2010      6    24
 5 a     2010      9    24
 6 a     2010      8    24
 7 a     2010      9    23
 8 a     2010     10    82
 9 b     2020     NA    NA
10 b     2020     13     1
11 b     2020     18     3
12 b     2020     24     6
13 b     2020     24     9
14 b     2020     23     8
15 b     2020     82     9

Upvotes: 3

Related Questions