【问题标题】:Using for loop in R: compute the column means在 R 中使用 for 循环:计算列均值
【发布时间】:2018-08-31 07:23:22
【问题描述】:

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

colMeans(mtcars)

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

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

凯特


非常感谢您的回复。 继网上的cmets之后,我更新了代码如下:

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

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()中的结果匹配了!!

再次感谢大家的帮助!!

凯特

【问题讨论】:

  • sapply(mtcars, mean) 会做到的
  • 你还没有初始化y2
  • out &lt;- c(); for (col in names(mtcars)) {out[[col]] &lt;- mean(mtcars[[col]])}; out
  • 你必须在循环之前初始化y2y2 &lt;- numeric()
  • 也可以试试seq_along(mtcars) 而不是c(1:11) 会更好。

标签: r for-loop


【解决方案1】:

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

# 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)
}

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2021-02-02
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 2016-12-22
    • 2021-10-02
    相关资源
    最近更新 更多