How do I create a table of value-frequency combinations arranged vertically,
> df = data.frame(fruit=c("apple", "banana", "cherry", "cherry", "apple", "banana", "apple", "date"));
> table(df$fruit)
apple banana cherry date
3 2 2 1
So far so good. But I'd like something that's like this (e.g. to basic manipulations and subsetting of values based on the frequency):
Fruit Freq
"apple" 3
"banana" 2
"cherry" 2
"date" 1
In SQL, that'd be SELECT fruit, COUNT(*) AS Freq FROM df GROUP BY fruit, and would yield a table that's like the starting point to this question: https://stats.stackexchange.com/questions/15574/how-to-convert-a-frequency-table-into-a-vector-of-values
Is there an easy way to do that in R? (Alternatively, does this indicate a mindset that's too 'SQL' and not enough 'R'?)
data.frame(table(df))
# df Freq
# 1 apple 3
# 2 banana 2
# 3 cherry 2
# 4 date 1
Or perhaps
setNames(data.frame(table(df)), c("Fruit", "Freq"))
# Fruit Freq
# 1 apple 3
# 2 banana 2
# 3 cherry 2
# 4 date 1
Using just base R, you can just convert it to a matrix which will be column oriented with the values as the row.names.
as.matrix(table(df))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With