使用循环对矩阵中的所有元素求和

Ann*_*nna 0 r matrix

在 R 中,我有一个 5x5 矩阵,P如下所示:

1  3  0  0  0
0  3  0  0  0
0  3  1  0  0
0  3  0  1  0
0  3  0  0  1
Run Code Online (Sandbox Code Playgroud)

并且想要总结它的所有元素。我知道我可以做到sum(P)并得到 19。但我想使用 for 或 while 循环来做到这一点。

一个想法是做

result <- 0
for(i in col(P)) { result <- result + sum(i)}
Run Code Online (Sandbox Code Playgroud)

然而,这让我知道总和 ( result) 是 75,即使在打印结果变量之后,我也不明白为什么。

Ron*_*hah 5

不确定,为什么要这样做,但我们可以使用类似 C 的循环结构,它为每一列和每一行循环并获取sum每个元素的 。

result = 0
for (i in 1:ncol(P)) {
  for (j in 1:nrow(P)) {
    result = result + P[i, j]
 }
}

result
#V1 
#19 
Run Code Online (Sandbox Code Playgroud)

while循环

i = 1
result = 0
while(i <= length(P)) {
  result = result + P[i]
  i = i + 1
}

result
#[1] 19
Run Code Online (Sandbox Code Playgroud)

@zx8754 建议的另一个选项是将其转换为向量并在每个元素上循环

result = 0
for (i in as.vector(P)) {
  result = result + i  
}

result
#[1] 19
Run Code Online (Sandbox Code Playgroud)