R - Rolling sum of two columns in data.table

故事扮演 提交于 2021-01-25 07:31:16

问题


I have a data.table as follows -

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.

          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.

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}

I am sure there must be a simple way to do this in one line using data.table.

Thanks


回答1:


You can add first v2 value to cumulative sum of 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


来源:https://stackoverflow.com/questions/65746251/r-rolling-sum-of-two-columns-in-data-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!