rcountfrequency-analysis

One large frequency table for multiple variables


I have a dataframe with 4 nominal variables with 3 levels each (A, B, C). I want to make a frequency table of height 4 and width 3, where each row contains the count of the levels for that variable.

df <- data.frame(var1=c('B', 'A', 'C', 'A', 'B', 'B', 'C'),
                 var2=c('A', 'A', 'A', 'A', 'B', 'B', 'C'),
                 var3=c('A', 'A', 'A', 'A', 'B', 'B', 'C'),
                 var4=c('A', 'A', 'A', 'A', 'B', 'B', 'B'))

head(df,10)
    var1 var2 var3 var4
1    B    A    A    A
2    A    A    A    A
3    C    A    A    A
4    A    A    A    A
5    B    B    B    B
6    B    B    B    B
7    C    C    C    B

The result should be something like this:

      A B C
var1  2 3 2
var2  4 2 1
var3  4 2 1 
var4  4 3 0

Is there an easy way to do this?


Solution

  • With some help from this answer, we can combine outputs from the table command, transpose it, and make it as a data frame with row.names coming from the column names of df.

    as.data.frame.matrix(t(table(unlist(df), row.names(df)[col(df)])), 
                         row.names = colnames(df))
    
         A B C
    var1 2 3 2
    var2 4 2 1
    var3 4 2 1
    var4 4 3 0