使用dplyr计算nycflights13数据集中ATL与BOS航班最大arr_delay的问题排查
Hey there! Let's get this sorted so you can get the exact max arrival delays for ATL and BOS that you're looking for.
What's Off With Your Current Code?
Your existing code filters the right flights and groups by destination, but you're using select() instead of an aggregation function to calculate the max delay. This means you're just keeping the arr_delay column (renamed) for every row in those groups, then sorting to show the single largest value across both destinations—so BOS's max gets lost in the full list of rows.
The Corrected Code
Here's how to adjust it to get one row per destination with its maximum arrival delay:
library(dplyr) library(nycflights13) flights %>% # Use %in% for cleaner multiple-value filtering filter(dest %in% c("ATL", "BOS")) %>% group_by(dest) %>% # Calculate the max delay per group, handle NA values summarize(max_arr_delay = max(arr_delay, na.rm = TRUE)) %>% # Optional: ungroup if you want a regular data frame instead of grouped ungroup() %>% as.data.frame()
Key Changes Explained
summarize()instead ofselect(): This is the critical fix.summarize()collapses each group (ATL and BOS) into a single row, calculating the maximumarr_delayfor that group.na.rm = TRUE: Theflightsdataset has some missingarr_delayvalues—adding this ensures we ignore them and get a valid max value.dest %in% c("ATL", "BOS"): A cleaner alternative to multiple==checks, especially if you ever need to add more destinations later.
What You'll Get
Running this code will return a data frame with exactly two rows:
| dest | max_arr_delay |
|---|---|
| ATL | 895 |
| BOS | 422 |
Which matches the exact result you were aiming for!
内容的提问来源于stack exchange,提问作者Patricia Sams

