'get the no. of observations in every level of factor after grouping by factors

in the data Arthritis of package 'vcd', after grouping by Treatment and Sex, i would like to get the no. and percentage of observations in every level (None, Some, Marked) of Improved. how to do it?



Solution 1:[1]

"count() lets you quickly count the unique values of one or more variables: df %>% count(a, b) is roughly equivalent to df %>% group_by(a, b) %>% summarise(n = n()) . count() is paired with tally() , a lower-level helper that is equivalent to df %>% summarise(n = n()) ."

Solution 2:[2]

I am not sure if there is a straightforward way to do this, but I would do this:

library(dplyr)
df2<-df %>% group_by(Treatment, Sex) %>% count()
df2$percent<-df2$n*nrow(df)/100

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PeteRlearner
Solution 2 juandelsur