Search code examples
rcumsum

R Cummulative sum in second column and offset


These are the values in my column

Col1
0.83
2.01
1.74
2.26
1.85

I am trying to create a second column which is a form of cummulative sum values from Col1 , the expected results should like this below

Col1    Col2
0.83    -
2.01    7.86
1.74    5.85
2.26    4.11
1.85    1.85

This is the logic behind the values in Col2

7.86 <-  2.01 + 1.74 + 2.26 +  1.85
5.85 <-  1.74 + 2.26 +  1.85
4.11 <-  2.26 +  1.85
1.85 <-  1.85

Any suggestions on achieving this is much appreciated.


Solution

  • We can do a rev and then do the cumsum

    c(NA, tail(rev(cumsum(rev(df$Col1))), -1))
    #[1]   NA 7.86 5.85 4.11 1.85
    

    data

    df <- structure(list(Col1 = c(0.83, 2.01, 1.74, 2.26, 1.85)),
      class = "data.frame", row.names = c(NA, 
     -5L))