简体   繁体   English

For循环求和R中矩阵的每一列

[英]For loop to sum each column of a matrix in R

For the following matrix: 对于以下矩阵:

my_matrix<-matrix(seq(from=1,to=100,by=2))

If I wanted the sum of each column calculated I would just put the command as follows: colSums(my_matrix) 如果我想计算每列的总和,则只需按如下所示放置命令: colSums(my_matrix)

However, I need to create equivalence to colSums(my_matrix) without using the colSums function and instead use for loop. 但是,我需要不使用colSums函数而创建与colSums(my_matrix) colSums函数,而应使用for循环。

Some please help!!! 一些请帮忙!!!

Sue, you can try this simple loop, hope it helps address your issue. 苏,您可以尝试这个简单的循环,希望它有助于解决您的问题。

sum <- 0
for(i in 1:ncol(my_matrix)){
  sum[i] <- sum(my_matrix[,i])
}

If you explicitly want to use for loop here is one way : 如果您明确想使用for循环,这是一种方法:

mat <- matrix(1:50, byrow = TRUE, ncol = 10)
all_vals <- numeric(ncol(mat))
for (i in seq(ncol(mat))) {
   all_vals[i] <- sum(mat[, i])
}

all_vals
#[1] 105 110 115 120 125 130 135 140 145 150

which gives same value as 与...具有相同的价值

colSums(mat)
#[1] 105 110 115 120 125 130 135 140 145 150

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM