3. 本题使用数据集 nycflights13::flights 和 nycflights13::planes (1) 利用 flights 和 planes,找出总飞行时间最长的前 10 种飞机型号ሺmodelሻ (10’) (2) 将数据集 flights 根据目的地ሺdestሻ进行分组,统计出各小组的行数,将行 数最多的前 10 个观测值保存为 top10_dest。用同样的操作,将数据集 flights 根据目的地ሺdestሻ进行分组,统计出每个目的地的平均起飞延误时 间ሺavg_dep_delayሻ,将结果命名为 avg_dep_delay(15’) (3) 将top10_dest与avg_dep_delay按照dest进行合并,得到数据集dest_delay, 并画图表示出以目的地数量为 x 轴、avg_dep_delay 为 y 轴的折线(10’)
时间: 2024-03-07 11:50:21 浏览: 298
(1)利用 flights 和 planes,找出总飞行时间最长的前 10 种飞机型号(model)
```
library(nycflights13)
library(dplyr)
# Join flights and planes data frames
flights_planes <- inner_join(flights, planes, by = "tailnum")
# Summarize total air time for each model
model_airtime <- flights_planes %>%
group_by(model) %>%
summarize(total_airtime = sum(air_time, na.rm = TRUE)) %>%
arrange(desc(total_airtime)) %>%
head(10)
# Print the top 10 models with the longest total air time
model_airtime
```
(2)将数据集 flights 根据目的地(dest)进行分组,统计出各小组的行数,将行数最多的前 10 个观测值保存为 top10_dest。用同样的操作,将数据集 flights 根据目的地(dest)进行分组,统计出每个目的地的平均起飞延误时间(avg_dep_delay),将结果命名为 avg_dep_delay。
```
# Find the top 10 destinations with the most flights
top10_dest <- flights %>%
group_by(dest) %>%
summarize(num_flights = n()) %>%
arrange(desc(num_flights)) %>%
head(10)
# Find the average departure delay for each destination
avg_dep_delay <- flights %>%
group_by(dest) %>%
summarize(avg_dep_delay = mean(dep_delay, na.rm = TRUE))
# Print the top 10 destinations with the most flights
top10_dest
# Print the average departure delay for each destination
avg_dep_delay
```
(3)将 top10_dest 与 avg_dep_delay 按照 dest 进行合并,得到数据集 dest_delay, 并画图表示出以目的地数量为 x 轴、avg_dep_delay 为 y 轴的折线。
```
# Merge top10_dest and avg_dep_delay by dest
dest_delay <- inner_join(top10_dest, avg_dep_delay, by = "dest")
# Plot the relationship between number of flights and average departure delay
library(ggplot2)
ggplot(dest_delay, aes(x = num_flights, y = avg_dep_delay)) +
geom_line() +
geom_point() +
xlab("Number of Flights") +
ylab("Average Departure Delay") +
ggtitle("Relationship between Number of Flights and Average Departure Delay by Destination")
```
阅读全文