Beloe是我的测试数据和代码,通过计算正数值来汇总tbl表。然后使用rollapply
和FUN sum添加5个连续的行计数。我在1,2 - 5,6,7,8 - 10,11行获得NA。
NA在5,6和10,11是由于缺少下一行而预期但我不明白为什么我在第1,2和7,8行获得NA。有些人可以看看代码并指出我的错误吗?
library(tidyverse)
library(zoo)
tbl<-tribble(
~z, ~x, ~y,
"x", "a", 2,
"x", "b", 1,
"x", "b", 3,
"y", "c", 3,
"x", "c", 1,
"x", "d", -1,
"x", "q", 2,
"x", "q", 2,
"x", "a", 2,
"x", "s", -1,
"y", "q", -1,
"y", "b", 3,
"x", "c", 3,
"y", "c", -1,
"y", "q", 1,
"y", "w", 2,
"y", "w", -2,
"y", "t", 2,
"y", "t", 1
)
tbl %>%
group_by(z, x) %>%
summarise(xy = sum(y>0, na.rm = T))%>%
mutate(zzz = rollapply(xy, width=5, sum, fill=NA))
输出:
# A tibble: 11 x 4
# Groups: z [2]
z x xy zzz
<chr> <chr> <int> <dbl>
1 x a 2 NA
2 x b 2 NA
3 x c 2 8
4 x d 0 6
5 x q 2 NA
6 x s 0 NA
7 y b 1 NA
8 y c 1 NA
9 y q 1 6
10 y t 2 NA
11 y w 1 NA