从向量计算行矩阵 cumsum
Calculate row-wise matrix cumsum from vector
给定一个向量,我想创建一个方阵,其中向量的元素在对角线上,并且有元素的逐行累积和。
示例向量:
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 方式(避免循环)是什么?
一种方法:
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
像这样:
> 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
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
给定一个向量,我想创建一个方阵,其中向量的元素在对角线上,并且有元素的逐行累积和。
示例向量:
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 方式(避免循环)是什么?
一种方法:
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
像这样:
> 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
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