Search code examples
rcumsum

adding value from previous row to subsequent ones, cumulatively in R


I am trying to add the last value from the previous row to the subsequent ones. For example

tmat = rbind(c(1,2,3), c(1,2,3), c(1,2,5))
tmat = as.data.frame(tmat)
tmat

  V1 V2 V3
1  1  2  3
2  1  2  3
3  1  2  5

changed to

  V1 V2 V3
1  1  2  3
2  4  5  6
3  7  8  11

I have tried various ways but I have a blind spot to this one.

new=list()
for(i in 2:nrow(tmat)){
    
new[[i]] =  cumsum(tmat[i,]+tmat[i-1,3])
        }
do.call(rbind, new)

Thanks for any help.


Solution

  • I'd use a loop since you need to compute the rows step by step...

    a <- 1:3
    aa <- rbind(a,a,a)
    aa[3,3] <- 6
    
    for(i in 1:(nrow(aa)-1)) {
      toadd <- aa[i,ncol(aa)]
      aa[i+1,] <- aa[i+1,] + aa[i, ncol(aa)]
    }
    aa
      [,1] [,2] [,3]
    a    1    2    3
    a    4    5    6
    a    7    8   12