Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find max per group with dplyr in R

Tags:

r

dplyr

I'm trying to get the carrier with the max value of flights during the summer months

max_flights_all_c<-nycflights13::flights %>%
   group_by(carrier,month)%>%
   filter(month==6 | month==7 | month==8 | month==9)%>%
    summarise(n=n()) 

Now I'm getting;

carrier month   n
9E  7   1494
9E  8   1456
9E  9   1540
AA  6   2757
AA  7   2882
AA  8   2856
AA  9   2614
AS  6   60
AS  7   62
AS  8   62
AS  9   60
B6  6   4622
B6  7   4984

but want to obtain only the max value of n for month each month.

like image 466
florecitas Avatar asked Mar 10 '23 20:03

florecitas


1 Answers

After the summarise step, we group by 'month' and get the max row of 'n' with slice.

max_flights_all_c <- nycflights13::flights %>%
                          group_by(carrier,month)%>%
                          filter(month %in% 6:9) %>%
                          summarise(n = n()) %>%
                          group_by(month) %>%
                          slice(which.max(n))
like image 184
akrun Avatar answered Mar 13 '23 13:03

akrun