This question already has an answer here:
This may seem like a very basic R question, but I'd appreciate an answer. I have a data frame in the form of:
col1 col2
a g
a h
a g
b i
b g
b h
c i
I want to transform it into counts, so the outcome would be like this. I've tried using table () function, but seem to only be able to get the count for one column.
a b c
g 2 1 0
h 1 1 0
i 0 1 1
How do I do it in R?
Using
f
from @Ananda you can usedcast
However, I'm writing this only in case you may need something more than just
table
(which for this case it's the simplest correct answer) in the future, like:I'm not really sure what you used, but
table
works fine for me!Here's a minimal reproducible example:
Notes:
table(df[c(2, 1)])
(ortable(df$V2, df$V1)
) to swap the rows and columns.as.data.frame.matrix(table(df))
to get adata.frame
as your output. (as.data.frame
will create a longdata.frame
, not one in the same output format you desire).