finding number of competitors on an airport using dplyr

Viewed 18

I am reviewing a dataset on flights and airport details. The dataset contains the following columns with the data about airport and flight details.

flight_date op_career tail_num flight_num origin origin_airport_ID dest_airport_ID dest
03/13/2019 AA N900EV 3503 SFO 11308 10397 LAX
03/13/2019 AA N900EZ 3502 SFO 11308 10397 LAX
03/13/2019 AS N686BR 3397 SFO 11308 10397 LAX
03/13/2019 YV N932LR 5804 SFO 11308 10397 LAX
03/14/2019 DL 255NV 515 SFO 11308 10397 LAX

I want to find the number of competitors on each airport.I am working with dplyr and I want to create a summary file which shows the airport and the competitors on that airport.

Airport competitors
SFO 4
LAX 4

I know you dont use count function in summary. I am just having trouble writing a function in summary file. Any suggestions?

1 Answers

We could use

library(dplyr)
library(tidyr)
df1 %>%
  group_by(origin, dest) %>% 
  summarise(competitors = n_distinct(op_career), .groups = 'drop') %>% 
  pivot_longer(cols = origin:dest, names_to = NULL,
    values_to = 'Airport') %>%
  select(Airport, competitors)

-output

# A tibble: 2 × 2
  Airport competitors
  <chr>         <int>
1 SFO               4
2 LAX               4
Related