Home > Software engineering >  Make a table of variable counts in R
Make a table of variable counts in R

Time:06-14

I am trying to make a table in R of frequency counts for several variables. I've found some examples of how to do this with a long dataset, but my dataset is wide and I haven't found an example that matches my situation.

Here is a sample of my existing dataframe. In the sample, the numbers under 'home', for example, are the number of times 'home' occurred as a category in another variable for that individual.

sample <- data.frame(id = c('a','b','c','d','e','f'),
                     home = c(3,6,5,2,4,5),
                     office = c(2,2,5,3,1,6),
                     other = c(4,1,3,1,5,6))

Dataframe I'm starting with

My goals is to get a table of variable counts so I can see where it makes sense to combine categories. My thought is that I'd want the variable names as row names with the frequency counts as the column names. Here is an example of what I'm hoping to get.

outcome <- data.frame('1' = c(NA, 1, 2),
                      '2' = c(1, 2, NA),
                      '3' = c(1, 1, 1),
                      '4' = c(1, NA, 1),
                      '5' = c(1, 1, 1),
                      '6' = c(1, 1, 1))

Desired table

R changes the variable to X1, but that would be the number of times a variable (e.g., home) occurs once.

CodePudding user response:

You could do:

as.data.frame(t(apply(sample[-1], 2, function(x) table(factor(x, 1:6)))))
#>        1 2 3 4 5 6
#> home   0 1 1 1 2 1
#> office 1 2 1 0 1 1
#> other  2 0 1 1 1 1
  • Related