Rowwise cumulative sum

前端 未结 2 1088
谎友^
谎友^ 2020-12-10 18:50

I have a data.table dt as follows.

df <- data.frame(t1 = rep(0,5), t3 = c(12, 5, 8,9, 5), t7= c(25, 48, 7, 9, 14))
dt <- setD         


        
相关标签:
2条回答
  • 2020-12-10 19:35

    If we need to do this by row, then one option is group by row, unlist, get the cumsum, convert to list and assign it to the columns

    dt[, (1:3) := as.list(cumsum(unlist(.SD))), 1:nrow(dt)]
    dt
    #    t1 t3 t7
    #1:  0 12 37
    #2:  0  5 53
    #3:  0  8 15
    #4:  0  9 18
    #5:  0  5 19
    

    Or another option is rowCumsums from matrixStats, which can be applied to a matrix

    library(matrixStats)
    dt[, (1:3) := as.data.table(rowCumsums(as.matrix(.SD)))]
    
    0 讨论(0)
  • 2020-12-10 19:40

    Another option use Reduce with accumulate=TRUE:

    dt[, names(dt) := Reduce(`+`, dt, accumulate = TRUE)]
    
    dt
    #   t1 t3 t7
    #1:  0 12 37
    #2:  0  5 53
    #3:  0  8 15
    #4:  0  9 18
    #5:  0  5 19
    
    0 讨论(0)
提交回复
热议问题