简体   繁体   English

R - data.table 中两列的滚动总和

[英]R - Rolling sum of two columns in data.table

I have a data.table as follows -我有一个 data.table 如下 -

dt = data.table(
  date = seq(as.Date("2015-12-01"), as.Date("2015-12-10"), by="days"),
  v1 = c(seq(1, 9), 20),
  v2 = c(5, rep(NA, 9))
)
dt
          date v1 v2
 1: 2015-12-01  1  5
 2: 2015-12-02  2 NA
 3: 2015-12-03  3 NA
 4: 2015-12-04  4 NA
 5: 2015-12-05  5 NA
 6: 2015-12-06  6 NA
 7: 2015-12-07  7 NA
 8: 2015-12-08  8 NA
 9: 2015-12-09  9 NA
10: 2015-12-10 20 NA

Question 1: I want to add the current row value of v1 with the previous row value of v2 so the output looks like the following.问题 1:我想将 v1 的当前行值与 v2 的前一行值相加,因此 output 如下所示。

          date v1 v2
 1: 2015-12-01  1  5
 2: 2015-12-02  2  7
 3: 2015-12-03  3 10
 4: 2015-12-04  4 14
 5: 2015-12-05  5 19
 6: 2015-12-06  6 25
 7: 2015-12-07  7 32
 8: 2015-12-08  8 40
 9: 2015-12-09  9 49
10: 2015-12-10 20 69

I have tried to use rollapplyr function to achieve this but failed.我曾尝试使用 rollapplyr function 来实现这一点,但失败了。

Question 2: Instead of adding (as in Question 1), I want to roll apply the function qma to the current row value of v1 with the previous row value of v2 qma <- function(x, y){(x+y+7)/2}问题 2:而不是添加(如问题 1),我想滚动应用 function qma 到 v1 的当前行值,前一行值为 v2 qma <- function(x, y){(x+y+7)/2}

I am sure there must be a simple way to do this in one line using data.table.我确信必须有一种简单的方法可以使用 data.table 在一行中执行此操作。

Thanks谢谢

You can add first v2 value to cumulative sum of v1 .您可以将first v2值添加到v1的累积总和中。

library(data.table)
dt[, v2:= first(v2) + c(0, cumsum(v1[-1]))]
dt

#          date v1 v2
# 1: 2015-12-01  1  5
# 2: 2015-12-02  2  7
# 3: 2015-12-03  3 10
# 4: 2015-12-04  4 14
# 5: 2015-12-05  5 19
# 6: 2015-12-06  6 25
# 7: 2015-12-07  7 32
# 8: 2015-12-08  8 40
# 9: 2015-12-09  9 49
#10: 2015-12-10 10 59

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM