R中某个窗口的移动总和 [英] Moving sum of a certain window in R

查看:8
本文介绍了R中某个窗口的移动总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to calculate a running sum of the next 5 rows. In this case, on row 1 it will show the sum of numbers from row 2 to row 6. The last 5 rows of the data frame can be filled with NA.

数据是这样的

在此处输入图片描述

理想的结果应该是这样的

And the ideal result would look like

在此处输入图片描述

谢谢!

推荐答案

首先,请考虑阅读如何制作一个出色的 R 可重现示例? 下次使用 dput 添加示例数据.

First, please consider to read How to make a great R reproducible example? and add sample data using dput next time.

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

这篇关于R中某个窗口的移动总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆