Suppose I want to calculate the proportion of different values within each group. For example, using the mtcars data, how do I calculate the relative f
mtcars
I wrote a small function for this repeating task:
count_pct <- function(df) { return( df %>% tally %>% mutate(n_pct = 100*n/sum(n)) ) }
I can then use it like:
mtcars %>% group_by(cyl) %>% count_pct
It returns:
# A tibble: 3 x 3 cyl n n_pct 1 4 11 34.4 2 6 7 21.9 3 8 14 43.8