【问题标题】:How to print cumulative sums of successive columns for each row ina matrix?如何打印矩阵中每一行的连续列的累积和?
【发布时间】:2022-01-24 04:43:27
【问题描述】:

我有一个相关性(方形)矩阵,我想显式打印所有行中元素的累积平方和。例如,它应该打印出类似“由于前 7 个主成分导致的变量 3 的方差是 ”之类的内容。我尝试了以下方法:

Fmat ## the original matrix (of correlations)

s <- matrix(data=NA, nrow=nrow(Fmat), ncol=ncol(Fmat)) ## create an empty matrix of cumulative sums

for (i in 1:nrow(Fmat)) {
  for (j in 1:ncol(Fmat)) {
    s[i, j] <- s + (Fmat[i, j])^2
    print(paste("Variance in variable", i, "due to the first", j, "PCs is", s[i, j]))
  }
}

我明白了

Error in s[i, j] <- s + (Fmat[i, j])^2 : 
  number of items to replace is not a multiple of replacement length

我曾尝试将 s 声明为标量而不是矩阵,但它继续累积所有行的列值,而不是为每个新行重新开始累积过程。

我猜问题出在下面一行

s[i, j] <- s + (Fmat[i, j])^2

【问题讨论】:

  • 最后一行是问题,s是一个矩阵,而Fmat[i,j]是一个数字,你可以将这两个加在一起得到一个新的矩阵s,其中每个元素都增加了Fmat [i,j],但是您现在不能将这个新矩阵分配给现有矩阵的一个元素,即 s[i,j]。你到底想在最后一行计算什么?
  • 我怀疑他们的意图类似于s[i, j] &lt;- (if (j &gt; 1L) s[i, j - 1L] else 0) + Fmat[i, j]^2

标签: r loops for-loop matrix


【解决方案1】:

您可以使用apply 预先计算您要打印的累积总和,如下所示:

X <- t(apply(Fmat * Fmat, 1L, cumsum))
n <- nrow(Fmat)
for (i in seq_len(n)) {
  for (j in seq_len(n)) {
    cat("Variance in variable", i, "due to the first", j, "PCs is", X[i, j], "\n")
  }
}

这里,矩阵X 的行i 包含矩阵Fmat 的行i 的平方元素的累积和。

要避免显式的for 循环,您也可以这样做:

f <- function(x, i, j) {
  cat("Variance in variable", i, "due to the first", j, "PCs is", x, "\n")
}
invisible(Map(f, x = t(X), i = t(row(X)), j = t(col(X))))

【讨论】:

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