library(dplyr)
mtcars %>%
count(cyl, gear) %>%
mutate(prop = prop.table(n))
See ?count
, basically, count
is a wrapper for summarise
with n()
but it does the group by for you. Look at the output of just mtcars %>% count(cyl, gear)
. Then, we add an additional variable with mutate
named prop
which is the result of calling prop.table()
on the n
variable we created after as a result of count(cyl, gear)
.
You could create this as a function using the SE
versions of count()
, that is count_()
. Look at the vignette for Non-Standard Evaluation in the dplyr
package.
Here's a nice github gist addressing lots of cross-tabulation variants with dplyr
and other packages.