Dplyr How to sort groups in sorted groups?

This is an extra bit of complication for dplyr functionality that I could not solve. Basically, I want to sort the second group in an already sorted group.

So I have this data.frame:

a_table <- data.frame(id=1:30, 
    grp1 = sample(LETTERS[1:5], 30, replace=TRUE, prob=c(1,1,2,2,3)), 
    grp2 = sample(letters[6:8], 30, replace=TRUE, prob=c(2,2,3))) 

I the first group grp1counts the records and arranges them, then for each grp1I count the values ​​of each grp2and order them.

My attempt to do this:

a_summary <- a_table %>% 
    group_by(grp1) %>% 
        mutate(frst_count = n()) %>% 
        arrange(desc(frst_count)) %>% 
    group_by(grp2) %>% 
        mutate(scnd_count = n()) %>% 
        arrange(desc(scnd_count))

But, obviously, something is missing because there is no group summariseand, therefore, no sorting of groups. Other attempts with summarisedo not isolate groups 1 and 2.

Thanks.

+4
source share
1 answer

group_by add = FALSE, , , , .

:

library(dplyr)
a_table %>% group_by(grp1) %>%
            mutate(frst_count = n()) %>%
            group_by(grp2, add = TRUE) %>%
            mutate(scnd_count = n()) %>%
            arrange(frst_count, scnd_count)
+8

Source: https://habr.com/ru/post/1617143/


All Articles