首页 > 解决方案 > 在 R 中使用 for 循环:计算列均值

问题描述

我尝试做“计算 mtcars 中每一列的平均值”的练习。我知道最简单的方法是使用colmeans()

colMeans(mtcars)

但我仍然想通过使用 for 循环找出方法。这是我的代码,但不起作用。我已经尝试了很多次,但无法找出错误(非常令人沮丧......)。您的回复将不胜感激。谢谢你。

for (i in c(1:11)) {   #mtcars has 11 columns
    y1<-mean(mtcars[,i])
    y2<-c(y1,y2)
}
y2

凯特


非常感谢您的回复。根据网上的评论,我更新了代码如下:

y2<-numeric()
 for (i in seq_along(mtcars)) {
 y1<-mean(mtcars[,i])
 y2<-c(y1,y2)
}
y2
 [1]   2.812500   3.687500   0.406250   0.437500  17.848750   3.217250
 [7]   3.596563 146.687500 230.721875   6.187500  20.090625

如果使用 colMeans()...

colMeans(mtcars)
    mpg        cyl       disp         hp       drat         wt       qsec 
 20.090625   6.187500 230.721875 146.687500   3.596563   3.217250  17.848750 
    vs         am       gear       carb 
 0.437500   0.406250   3.687500   2.812500 

看到列表完全相反(与第一部分中的代码相比)非常有趣。然后我发现了 y2<-c(y1,y2) 中的问题,如果我将原始 y2<-c(y1,y2) 更改为...

y2<-c(y2,y1) 

最终版本....

y2<-numeric()
 for (i in seq_along(mtcars)) {
 y1<-mean(mtcars[,i])
 y2<-c(y2,y1)
}
y2
[1]  20.090625   6.187500 230.721875 146.687500   3.596563   3.217250
[7]  17.848750   0.437500   0.406250   3.687500   2.812500

这个结果终于和 colMeans() 中的结果匹配了!!

再次感谢大家的帮助!!

凯特

标签: rfor-loop

解决方案


这是使用循环执行此操作的标准方法:

# Extract the number of columns
ncols <- length(mtcars)
# Initialize your mean vector (this will make the loop run much faster)
column_means <- vector(mode = "numeric", length = ncols)
# Now loop through each column
for (i in 1:ncols) {   
  column_means[i] <- mean(mtcars[[i]])
}
# Why not turn our mean vector into a named vector so we can better make sense 
# of the numbers
names(column_means) <- names(mtcars)
column_means

       mpg        cyl       disp         hp       drat         wt       qsec         vs         am       gear 
 20.090625   6.187500 230.721875 146.687500   3.596563   3.217250  17.848750   0.437500   0.406250   3.687500 
      carb 
  2.812500 

但是如何使原始代码工作?

y2 <- NULL
for (i in c(1:11)) {   #mtcars has 11 columns
    y1<-mean(mtcars[,i])
    y2<-c(y2, y1)
}

推荐阅读