You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用dplyr计算nycflights13数据集中ATL与BOS航班最大arr_delay的问题排查

Fixing Your Flight Delay Max Calculation

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 of select(): This is the critical fix. summarize() collapses each group (ATL and BOS) into a single row, calculating the maximum arr_delay for that group.
  • na.rm = TRUE: The flights dataset has some missing arr_delay values—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:

destmax_arr_delay
ATL895
BOS422

Which matches the exact result you were aiming for!

内容的提问来源于stack exchange,提问作者Patricia Sams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 14:12:34