Search code examples
rdataframesumcalculated-columns

How to sum a column over successively less rows?


#Want data frame to go from this...
a<- c(1,2,3,4,5)
b<- c(0,0,0,0,0)
ab<-cbind(a,b)
print(ab)
  a b
[1,] 1 0
[2,] 2 0
[3,] 3 0
[4,] 4 0
[5,] 5 0

#to this...

     a  b
[1,] 1 15
[2,] 2 14
[3,] 3 12
[4,] 4  9
[5,] 5  5

what's happening here is to have the first value of column b to be the sum of the whole column (1+2+3+4+5=15). Its the column sum.

What we want for the next value of column b is to be the column sum of everything but the first row (2+3+4+5= 14)

The third column should be (3+4+5 =12) and so on for n number of rows.

Ive tried to make a for loop however I haven't had any success.

I'm stuck trying to figure out a way to sum a column value and everything below it using R. This is part of a lifetable calculation for ecology and any help would be appreciated.


Solution

  • You could use rev function:

    a<- c(1,2,3,4,5)
    b <- rev(cumsum(rev(a)))
    cbind(a, b)