[求数据平均值时参考a循环值

问题描述 投票:0回答:1

我有一个关于作物单产的数据框,叫做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

我不确定是否有我不知道的特定语法,将不胜感激!

r for-loop row average tibble
1个回答
0
投票
library(magrittr) x = lapply(2009:2018, function(x){ wdata$Yield[ wdata$year == x ] %>% mean })
然后我们可以按行绑定它:

rbind(wdata, data.frame(Year = 1, Region = "Average", Yield = x))

© www.soinside.com 2019 - 2024. All rights reserved.