Search code examples
rdata.tablerolling-computationrollapply

R - Rolling sum of two columns in data.table


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


Solution

  • 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