从向量计算行方式矩阵cumsum

时间:2015-01-27 11:39:24

标签: r matrix

给定一个向量我想创建一个方形矩阵,其中向量的元素在对角线上,并且有逐行的元素。

示例矢量:

vec <- c(1, 2, 3, 4)

必需的输出:

     [,1] [,2] [,3] [,4]
[1,]    1    3    6   10
[2,]    0    2    5    9
[3,]    0    0    3    7
[4,]    0    0    0    4

现在,我正在使用双循环函数:

diagSum <- function(vec) {
  mat <- diag(vec)
  for (i in seq(nrow(mat))) {
    for (j in seq(i, ncol(mat))) {
      if (j > i) {
        mat[i, j] <- mat[i, j - 1] + mat[j, j]      
      }
    }
  }
  mat
}

这样做的R-way(避免循环)是什么?

3 个答案:

答案 0 :(得分:8)

m <- matrix(vec, nrow = length(vec), ncol = length(vec), byrow =TRUE)
m[lower.tri(m)] <- 0
t(apply(m, 1, cumsum))
#     [,1] [,2] [,3] [,4]
#[1,]    1    3    6   10
#[2,]    0    2    5    9
#[3,]    0    0    3    7
#[4,]    0    0    0    4

答案 1 :(得分:4)

一种方法:

x <- c(1, 2, 3, 4)
rbind(cumsum(x), t(sapply(1:3, function(y) c(rep(0, y), cumsum(x[-(1:y)])) )))
#       [,1] [,2] [,3] [,4]
# [1,]    1    3    6   10
# [2,]    0    2    5    9
# [3,]    0    0    3    7
# [4,]    0    0    0    4

答案 2 :(得分:4)

像这样:

> x=c(1, 2, 3, 4)

> do.call(rbind, lapply(1:length(x)-1, function(u) {x[0:u]=0;cumsum(x)}))
#     [,1] [,2] [,3] [,4]
#[1,]    1    3    6   10
#[2,]    0    2    5    9
#[3,]    0    0    3    7
#[4,]    0    0    0    4