Say we have the following data:
user <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
type <- c('new', 'recent', 'recent', 'old', 'recent', 'new', 'new', 'old', 'new', 'new', 'new', 'recent')
df <- data.frame(user, type)
If we compute the table, we get the following:
table(df$type)
> new old recent
6 2 4
I am looking for a function that takes in this table data and transforms it into a dataframe, regardless of the number of columns. Ideally, the dataframe would look like this:
type count
new 6
old 2
recent 4
CodePudding user response:
This does the job:
df2 <- as.data.frame(table(df$type))
> df2
Var1 Freq
1 new 6
2 old 2
3 recent 4
You can rename Var1 and Freq if you want:
colnames(df2) <- c("type", "count")
> df2
type count
1 new 6
2 old 2
3 recent 4
CodePudding user response:
Here are some options
> stack(table(df$type))
values ind
1 6 new
2 2 old
3 4 recent
> as.data.frame(table(df$type))
Var1 Freq
1 new 6
2 old 2
3 recent 4