我仍然是R的新手并尝试以特定方式汇总数据。为了说明这里,我正在使用来自nasaweather包的天气数据。例如,我想获得特定日期的平均温度,并显示该数据集中包含的3个来源和12个月。
我想我可以使用以下代码完成它,我指定我感兴趣的那一天,创建一个空数据框以填充,然后在我计算平均温度的月份运行for循环对于每个来源,用月份来约束它们,然后将它们绑定到数据框。最后,我调整列名称并打印出结果:
library(nasaweather)
library(magrittr)
library(dplyr)
query_day = 15
data_output <- data.frame(month = numeric(),
EWR = numeric(),
JFK = numeric(),
LGA = numeric())
for (i in 1:12) {
data_subset <- weather %>%
filter(day == query_day, month == i) %>%
summarize(
EWR = mean(temp[origin == "EWR"]),
JFK = mean(temp[origin == "JFK"]),
LGA = mean(temp[origin == "LGA"]))
data_output <- rbind(data_output, cbind(i, data_subset))
rm(data_subset)
}
names(data_output) <- c("month", "EWR", "JFK", "LGA")
print(data_output)
在我手中,这产生以下结果:
month EWR JFK LGA
1 1 39.3725 39.0875 38.9150
2 2 42.1625 39.3425 42.9050
3 3 37.4150 36.7775 37.3025
4 4 50.1275 48.1550 49.2050
5 5 58.8725 55.7150 59.1575
6 6 70.7825 70.2950 71.5700
7 7 86.9900 85.1225 87.2000
8 8 69.2075 69.0725 69.9425
9 9 60.6350 61.2125 61.7375
10 10 59.8850 58.3850 60.5150
11 11 45.7475 45.1700 49.0700
12 12 32.4950 38.0975 34.0325
这正是我想要的。我只是觉得我的代码似乎太复杂了,想问一下是否有更简单的方法来完成这项工作?
答案 0 :(得分:1)
你的代码存在各种各样的问题......但主要的问题是你没有先成为group_by。一旦你把它包括在内,这就变得容易了。首先查看我对您的代码的评论,然后查看底部的最终代码:
LoadBalancer
收益率:
library(nasaweather) ## Wrong package
# library(magrittr) ## not needed, it's called by dplyr
library(dplyr)
query_day = 15
# data_output <- data.frame(month = numeric(), ## We won't need to specify this explicitly
## (but you are right that you should specify this in a for loop. Go one step
## further by actually telling the data.frame how many rows to expect.
## But not in this case cause we won't use for loop)
# EWR = numeric(),
# JFK = numeric(),
# LGA = numeric())
for (i in 1:12) { ## You don't need to do a for loop... you can do it with the summarize_by function.
data_subset <- weather %>%
filter(day == query_day, month == i) %>%
summarize( ## Before doing summarize, you need a group_by to say what to summarize_by
EWR = mean(temp[origin == "EWR"]),
JFK = mean(temp[origin == "JFK"]),
LGA = mean(temp[origin == "LGA"]))
data_output <- rbind(data_output, cbind(i, data_subset)) ## If you're doing the group_by, this step isn't required.
# rm(data_subset) ## You don't have to remove temporary datasets...
## When the for loop ends, they are automatically removed.
}
names(data_output) <- c("month", "EWR", "JFK", "LGA")
print(data_output)
################### Better code:
library(nycflights13) ## your the package you waant is nycflights13... not nasaweather
library(dplyr)
query_day = 15
weather %>%
filter(day == query_day) %>%
group_by(month) %>%
summarize(
EWR = mean(temp[origin == "EWR"]),
JFK = mean(temp[origin == "JFK"]),
LGA = mean(temp[origin == "LGA"])) -> data_output
data_output