0

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

jangorecki
  • 16,384
  • 4
  • 79
  • 160
Saurabh
  • 1,566
  • 10
  • 23
  • 1
    Sure. I have created another post for this follow up question - https://stackoverflow.com/questions/65746358/r-rolling-a-function-on-two-columns-in-data-table – Saurabh Jan 16 '21 at 03:57

1 Answers1

2

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • The data above was simple just as an example. In reality, the numbers in v1 and v2 can be random. I have changed the data.table a bit. Can you please update your solution? – Saurabh Jan 16 '21 at 04:05
  • @Saurabh Did you try my answer on your updated data? It still works for me and gives the expected output as shown. – Ronak Shah Jan 16 '21 at 04:08