【问题标题】:how to add up the column (cumulative sum) of the matrix in R?如何将R中矩阵的列(累积和)相加?
【发布时间】:2020-06-28 21:48:21
【问题描述】:

我有一个关于将矩阵的列相加的问题 例如:

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

I want it to be
      [,1] [,2] [,3]
[1,]    1    4    5
[2,]    2    6    8

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以通过循环遍历指定为 1 的 applyMARGIN 的行并转置输出来对每一行应用 cumsum

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

    或者使用for 循环

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

    或者另一种选择是将其拆分为list 向量与asplit,然后将Reduce+accumulate = TRUE 分开

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

    或使用方便的函数rowCumsums 来自matrixStats

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

    数据

    m1 <- cbind(1:2, 3:4, 1:2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-11
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多