1

I recently posted a question on how to calculate a moving average grouped over two or more variables. I was shown that using the dplyr package you can use the filter to do what I was after.

However this only works if there are enough variables within each group combo to create the average. when I try the following suggestion:

 AVG2 <- (game %>% group_by(Team, Player) %>% mutate(AVG2 = stats::filter(Goals, c(0,1/2,1/2), sides = 1 )))$AVG2
 AVG3 <- (game %>% group_by(Team, Player) %>% mutate(AVG2 = stats::filter(Goals, c(0,1/3,1/3,1/3), sides = 1 )))$AVG3

I get the error:

"Error: 'filter' is longer than time series"

Is there a way to do this so that r just gives those that don't have enough values 'NA' rather than erroring out?

Here is my desired output:

   no   Team    Player  Goals   **AVG2**    **AVG3**
   1    I       S       5       NA      NA
   2    B       S       2       NA      NA
   3    B       S       7       NA      NA
   4    B       O       3       NA      NA
   5    B       O       9       NA      NA
   6    I       O       6       NA      NA
   7    I       O       3       NA      NA
   8    I       S       7       NA      NA
   9    I       O       1       4.5     NA
   10   B       S       7       4.5     NA
   11   I       S       3       6       NA
   12   I       Q       8       NA      NA
   13   B       S       3       7       5.33
   14   I       O       4       2       3.33
   15   B       P       1       NA      NA
   16   I       S       9       5       5
   17   B       S       4       5       5.67
   18   B       Z       6       NA      NA
   19   I       S       3       6       6.33
   20   I       O       8       2.5     2.67
   21   B       S       3       3.5     4.67
   22   I       O       4       6       4.33
   23   B       O       1       6       NA
   24   I       S       9       6       5
   25   B       S       4       3.5     3.33
   26   B       O       6       5       4.33
   27   I       J       6       NA      NA

here is the code to recreate the initial table in r:

Team <- c('I','B','B','B','B','I','I','I','I','B','I','I','B','I','B','I','B','B','I','I','B','I','B','I','B','B','I')
Player <- c('S','S','S','O','O','O','O','S','O','S','S','Q','S','O','P','S','S','Z','S','O','S','O','O','S','S','O','J')
Goals <- c(5,2,7,3,9,6,3,7,1,7,3,8,3,4,1,9,4,6,3,8,3,4,1,9,4,6,6)
game <- data.frame(Team, Player, Goals)
greeny
  • 425
  • 1
  • 6
  • 20
  • The `rollapply` solution that I provided to your prior problem at http://stackoverflow.com/questions/35249019/grouped-moving-average-in-r works on this one too. – G. Grothendieck Feb 09 '16 at 05:40
  • Or roll-your-own function to check that the length of the filter is appropriate - `mvavgchk <- function(x,n) if(length(x) >= n) filter(x,rep(1,n)/n, sides=1) else NA_real_` – thelatemail Feb 09 '16 at 05:47

0 Answers0