首页 > 解决方案 > 查找数据的平均值时引用一个 for 循环值

问题描述

我有一个名为 wwdata 的作物产量数据框,看起来有点像这样:

Year Region       Yield
2009 northeast    9.1
2009 northwest    8
2009 yorkshire    7.8
2009 eastmidlands 8.1
2009 westmidlands 7.9
...

数据持续了大约 100 行,从 2009 年到 2018 年。

我想尝试使用 for 循环找到这种作物每年的平均产量,并使用 tibble 将其添加到数据框的底部,以便我可以将其绘制在 ggplot 上。这是我尝试使用的代码:

x <- seq(2009,2018,1)
for (val in x) {
  y <-  wwdata[wwdata$Year == x]
  average_x <- mean(y$yield)
  wwdata <- add_row(Year = x, Region = "Average", Yield = average_x ) 
}

这通常适用于其他语言,但在 R 中,它似乎不理解“x”是当前的 for 循环值。错误:

Error in `[.data.frame`(wwdata, wwdata$Year == z) : 
  undefined columns selected

我不确定是否有我不知道的特定语法,感谢任何帮助!

标签: rfor-looprowaveragetibble

解决方案


    library(magrittr)

    Z  = lapply(2009:2018, function(x){
            data.frame(Year = x, 
            Region = "Average",
            wdata$Yield[ wdata$year == x ] %>% mean)
         })%>% do.call(what = "rbind")

然后我们可以按行绑定它:

rbind(wdata, Z)

推荐阅读