【问题标题】:cumulative sum for rows upto select row number followed by summing up columns matrix in R行的累积总和,直到选择行号,然后对 R 中的列矩阵求和
【发布时间】:2015-07-08 23:57:54
【问题描述】:

我正在尝试对矩阵进行以下求和:

假设矩阵是:

    mat <- matrix(c(1:5,rep(0,7),c(1:7),rep(0,5),c(1:10), 0,0), 12,3)

我想分别对列号 1、2、3 的行号 5、7、10 的行进行累积求和。 (真实数据可以有任意数量的行和列)。

目前,我一直在使用以下代码:

    sum1 <- matrix(rep(0, 36), 12, 3)
    row_index <- c(5,7,10)
    for (k in 1:3) {
      sum1[1:row_index[k], k] <- cumsum(mat[1:row_index[k], k])
    }
    sum1 <- matrix(apply(sum1,1,sum))

首先,我有矩阵和 row_index。我想避免使用循环,因为数据有很多列。我想知道是否有办法做到这一点。

【问题讨论】:

  • 直截了当:你在每一列上独立地做一个cumsum,然后你rowsum跨越这些累积总和并平展结果? (最后的apply(sum1, 1, sum) - 你没有提到这个,但这就是你在做什么?)
  • 并且将列中的剩余值(您 cumsum 超过,例如第 1 列中的索引 6:12)总是为 0,还是仅出于本示例的目的?
  • 如果@mathematical.coffee 说的是真的,你可以这样做:rowSums(apply(replace(mat, mat==0, NA),2,cumsum),na.rm=TRUE)
  • @mathematical.coffee 抱歉,我忘了在文中提及,但是是的,你没看错。我想在最后总结所有列。我没有cumsum 的所有索引理想情况下应该为零,但它们可能是负数,在这种情况下需要过滤。所以我喜欢@thelatemail 的方法,因为它允许我在给定任何条件的情况下替换所有元素。谢谢你们!

标签: r matrix cumsum


【解决方案1】:
depth <- c(5,7,10)
mapply( function(x,y) cumsum(mat[1:x, y]), depth, seq_along(depth) )

[[1]]
[1]  1  3  6 10 15

[[2]]
[1]  1  3  6 10 15 21 28

[[3]]
 [1]  1  3  6 10 15 21 28 36 45 55

【讨论】:

  • 感谢您的帮助!我使用了您的代码的一个变体并且它有效。
【解决方案2】:

首先,定义一个函数:

sumcolumn <- function(rows, columns, mat){
  cumsum(mat[1:rows, columns])
}

然后在列/行向量上使用 mapply:

mapply(sumcolumn, rows = c(5, 7, 10), columns = c(1, 2, 3), MoreArgs = list(mat = mat))

【讨论】:

  • 非常感谢。但我希望最后得到列总和。所以,我修改了你的代码并且它有效。 sumcolumn &lt;- function(rows, columns, mat){ return(c(cumsum(mat[1:rows, columns]),rep(0,(nrow(mat)-rows)))) } sum1 &lt;- matrix(apply(mapply(sumcolumn, rows = c(5, 7, 10), columns = c(1, 2, 3), MoreArgs = list(mat = mat)),1,sum)) 非常感谢!
猜你喜欢
  • 2018-07-05
  • 2017-12-14
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多