在R中统计每架飞机首次1小时以上延误前的航班数量
Solution: Count Flights Before First 1+ Hour Delay per Plane
Great question! Let's work through this step by step to get the count of flights each plane made before its first 60+ minute arrival delay.
First, let's fix a couple of issues with your current approach:
- Your grouping includes too many columns (like
arr_delay), which splits a single plane's flights into unnecessary subgroups. - Using
first()without properly sorting flights by time won't give you the chronological first delay, which is critical here.
Step-by-Step Code & Explanation
Here's a tidyverse-based solution that correctly orders flights, tracks the first delay, and counts the preceding flights:
library(tidyverse) flight_delay_summary <- flights %>% # Keep only relevant columns to simplify processing select(tailnum, year, month, day, dep_time, arr_delay) %>% # **Critical**: Sort flights by plane, then by date/time to ensure chronological order arrange(tailnum, year, month, day, dep_time) %>% group_by(tailnum) %>% # Mark which flights had a 60+ minute delay mutate(is_long_delay = arr_delay > 60) %>% # Track whether we've already seen the first long delay (cumsum turns TRUE once a delay occurs) mutate(has_seen_first_delay = cumsum(is_long_delay) >= 1) %>% # Filter to keep only flights up to and including the first long delay filter(!has_seen_first_delay | (has_seen_first_delay & is_long_delay)) %>% # Calculate the number of flights *before* the first long delay summarise( flights_before_first_long_delay = n() - ifelse(any(is_long_delay), 1, 0), # Optional: Add a flag if the plane ever had a long delay ever_had_long_delay = any(is_long_delay) )
How This Works:
- Sorting: We first sort each plane's flights by date and departure time to make sure we're checking delays in the order they actually happened.
- Delay Flag:
is_long_delaysimply marks each flight as meeting the 60+ minute delay condition. - Track First Delay:
has_seen_first_delayusescumsum()—once aTRUE(delay) is encountered, all subsequent rows becomeTRUE, letting us know we've passed the first delay point. - Filter Rows: We keep all flights before the first delay, plus the first delay flight itself.
- Count Preceding Flights: For planes that had a delay, we subtract 1 from the total row count (to exclude the delay flight itself). For planes that never had a delay, we just use the total number of flights.
Example Check
Looking at your sample data:
- For
D942DN, the first flight was already a 91-minute delay. Soflights_before_first_long_delaywill be 0. - For
N0EGMQ, the second flight was the first delay. Soflights_before_first_long_delaywill be 1.
This will give you a clean summary for all 4,044 unique tailnumbers.
内容的提问来源于stack exchange,提问作者Rob Glassenbury
相关产品推荐
相关产品推荐

