0

Table I have:

DT <- data.frame(A=1:5*10, B=1:5*-1)
DT
   A  B
1 10 -1
2 20 -2
3 30 -3
4 40 -4
5 50 -5

Table I want:

C=A+B+C(n-1)

   A  B  C
1 10 -1  9
2 20 -2 27
3 30 -3 54
4 40 -4 90
5 50 -5 135

I have reference below link and try to apply but fail:

Use a value from the previous row in an R data.table calculation

DT$C<-DT$A+DT$B+shift(DT$C)
Community
  • 1
  • 1
abcdabc
  • 1
  • 1

2 Answers2

2

If I am not missing something, this will do the trick:

DT <- data.table(A=1:5*10, B=1:5*-1)
DT[, C := cumsum(A + B)]
Bulat
  • 6,869
  • 1
  • 29
  • 52
0

With dplyr

library(dplyr)
DT %>% 
     mutate(C= cumsum(A+B))
#   A  B   C
#1 10 -1   9
#2 20 -2  27
#3 30 -3  54
#4 40 -4  90
#5 50 -5 135
akrun
  • 874,273
  • 37
  • 540
  • 662