我有一个关于添加矩阵列的问题,例如:
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
我们可以cumsum
通过用apply
和MARGIN
指定为1的行循环并套用输出来对每一行应用
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句