r - 查找数据的平均值时引用一个 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
我不确定是否有我不知道的特定语法,感谢任何帮助!
解决方案
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)
推荐阅读
- c# - 如何在 C# 中将 git 哈希转换为长度为 20 的字节数组?
- android - Android - Volley 库:SSL 生产环境中的会话过期问题
- javascript - 从另一个元素实例引用 Vue 实例
- java - 如何判断java类是否匿名?
- bash - 如何使用键盘输入模式打印每个块?
- azure - 应用注册认证密钥在哪里?
- vb.net - 如何防止复选框 Checkchanged 事件在 VB.Net 中触发
- python - Django-将用户名字段更改为 BigAutoField?
- php - 无法创建新的 Laravel 项目 - 解压缩 -qq 超时超过 300
- java - 将 Java 10 与 Spring MVC 5 一起使用