R中某个window的移动和

Moving sum of a certain window in R

我想计算接下来 5 行的 运行 总和。在这种情况下,第 1 行将显示第 2 行到第 6 行的数字总和。数据框的最后 5 行可以用 NA 填充。

数据是这样的

enter image description here

理想的结果应该是这样的

enter image description here

谢谢!

您可以使用 zoo 包中的 rollsum。

library(zoo)
rollsum(df$column, 5)

第二个参数是求和的行数,这里是5。

首先,请考虑阅读How to make a great R reproducible example?并在下次使用dput 添加样本数据。

df <- data.frame(t = c(1,3,5,2,1,3,4,6,7,2,1))

library(zoo)
library(dplyr)

df$V2 <- rollsum(lead(df$t), 5, align = "left", fill = NA)
df

   t V2
1  1 14
2  3 15
3  5 16
4  2 21
5  1 22
6  3 20
7  4 NA
8  6 NA
9  7 NA
10 2 NA
11 1 NA