how to add up the column (cumulative sum) of the matrix in R?

后端 未结 1 1591
别跟我提以往
别跟我提以往 2021-01-23 17:26

I have a question about adding up the column of the matrix for example:

I have a matrix
      [,1] [,2] [,3]
[1,]    1    3    1
[2,]    2    4    2

I want it to         


        
相关标签:
1条回答
  • 2021-01-23 18:06

    We can apply cumsum on each row by looping over the rows with apply and MARGIN specified as 1 and transpose the output

    t(apply(m1, 1, cumsum))
    #     [,1] [,2] [,3]
    #[1,]    1    4    5
    #[2,]    2    6    8
    

    Or with a for loop

    for(i in seq_len(ncol(m1))[-1]) m1[,i] <- m1[, i] + m1[, i-1]
    

    Or another option is to split it a list of vectors with asplit and then Reduce with + and accumulate = TRUE

    do.call(cbind, Reduce(`+`, asplit(m1, 2), accumulate = TRUE))
    #     [,1] [,2] [,3]
    #[1,]    1    4    5
    #[2,]    2    6    8
    

    or with a convenient function rowCumsums from matrixStats

    library(matrixStats)
    rowCumsums(m1)
    #      [,1] [,2] [,3]
    #[1,]    1    4    5
    #[2,]    2    6    8
    

    data

    m1 <- cbind(1:2, 3:4, 1:2)
    
    0 讨论(0)
提交回复
热议问题