Reputation: 59
I have several columns in my source data frame containing the same three possible variables (1, 2 and 3) over several hundred rows. I'm using the table function to summarize each column as shown here
column1 <- table(data$column1)
column2 <- table(data$column2)
column3 <- table(data$column3)
...
These tables print out results of the form below
1 2 3
6 74 300
I'm trying to combine all of these tables into one data frame of this form
1 | 2 | 3 | |
---|---|---|---|
column1 | 6 | 74 | 300 |
column2 | 2 | 87 | 298 |
column3 | 4 | 57 | 489 |
How do I make this happen? Thank you!
Upvotes: 0
Views: 84
Reputation: 59
Got a solution using rbind from reddit. It does exactly what I was looking for.
#selected all tables in the environment
tables = sapply(.GlobalEnv, is.table)
#rbinded them
allquestions <- do.call(rbind, mget(names(tables)[tables]))
Upvotes: 0
Reputation: 10771
We can use the tidyverse
, suppose your data is called dat
:
library(tidyverse)
dat %>%
pivot_longer(cols = everything()) %>%
count(name, value) %>%
pivot_wider(names_from = value, values_from = n)
# name `1` `2` `3`
# 1 column1 6 74 300
# 2 column2 2 87 298
# 3 column3 4 57 489
Upvotes: 1