我最近发布了一个关于如何计算两个或更多变量的移动平均值的问题。我被证明使用dplyr包你可以使用过滤器来完成我想要的工作。
但是,只有在每个组合组合中有足够的变量来创建平均值时,这才有效。当我尝试以下建议时:
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
我收到错误:
&#34;错误:&#39;过滤&#39;比时间序列更长&#34;
有没有办法做到这一点,以便r只是给那些没有足够价值的人&#39; NA&#39;而不是错误?
这是我想要的输出:
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
这是在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)