Search code examples
rdplyrfrequencyanalysis

frequency count of multiple variables in R


I have multiple variables in my dataframe. I want to check the individual frequency counts of some of the selected variables more from QA perspective of large datasets.e.g

ID Q1 Q2 Q3
1  1  2  3
2  2  1  2 
3  3  2  1
4  1  2  3
5  2  3  1

So, I should get the frequency count of Q1 & Q2, my selected variables, as the output below

Q1 1 - 2
   2 - 2
   3 - 1

Q2 1 - 1
   2 - 3
   3 - 1

I tried table(), but it seeems like I would have to write this function multiple times which I want to avoid.

table(df$Q1)
table(df$Q2)

Is there any other way to achieve this?


Solution

  • You can use apply with table

    apply(df[-1], 2, table)
    
    #  Q1 Q2 Q3
    #1  2  1  2
    #2  2  3  1
    #3  1  1  2
    

    Or if you want it for selected rows only which you want to specify using their names you can use,

    apply(df[c("Q1", "Q2")], 2, table)
    
    
    #  Q1 Q2
    #1  2  1
    #2  2  3
    #3  1  1