dplyr, calculate the max_arr_ delay for flights to ATL and BOS

Viewed 20

The dataset is nycflights13.R. I'm unable to get the required answer:

  1. ATL 895
  2. BOS 422

When I run my code I can get the top for ATL but not for BOS, I'm having trouble narrowing down the resulting df to just the two answers.

flights %>%
    filter(dest == 'ATL' | dest == 'BOS') %>%
    group_by(dest) %>%
    select(dest, max_arr_delay = arr_delay) %>%
    arrange(desc(arr_delay) %>%
    as.data.frame()

I am missing the step that would limit this dataframe. I get both the max answers for ATL and BOS but BOS is buried by the arrange function. How do I limit this so I get both the max values for just ATL and BOS.

1 Answers

Using dplyr::slice_max you could do:

library(nycflights13)
library(dplyr)

flights %>%
  filter(dest %in% c("ATL", "BOS")) %>%
  select(dest, max_arr_delay = arr_delay) %>%
  group_by(dest) %>%
  slice_max(max_arr_delay, n = 1)
#> # A tibble: 2 × 2
#> # Groups:   dest [2]
#>   dest  max_arr_delay
#>   <chr>         <dbl>
#> 1 ATL             895
#> 2 BOS             422

Or using summarise:

library(nycflights13)
library(dplyr)

flights %>%
  filter(dest %in% c("ATL", "BOS")) %>%
  group_by(dest) %>%
  summarise(max_arr_delay = max(arr_delay, na.rm = TRUE))
#> # A tibble: 2 × 2
#>   dest  max_arr_delay
#>   <chr>         <dbl>
#> 1 ATL             895
#> 2 BOS             422
Related