I have a dataframe and I want to output a two-way contingency table from two of the columns. They both have values "Too Little", "About Right" or "Too Much".
I'm typing
df %>%
filter(!is.na(col1)) %>%
group_by(col1) %>%
summarise(count = n())
for both of them separately and get something like this:
col1 count
<fctr> <int>
Too Little 19259
About Right 9539
Too Much 2816
What I would like to achieve is this:
Too Little About Right Too Much Total
col1 19259 9539 2816 31614
col2 20619 9374 2262 32255
Total 39878 18913 5078 63869
I've been trying to use table function
addmargins(table(df$col1, df$col2))
But the result is not what I want
Too Little About Right Too Much Sum
Too Little 13770 4424 740 18934
About Right 4901 3706 700 9307
Too Much 1250 800 679 2729
Sum 19921 8930 2119 30970
I'd give
tabulate
a try, which is the foundation fortable
(see?tabulate
). For example giventhen you could do
Or (via @thelatemail) just