Search code examples
rfrequencydummy-variable

How to create a table shows frequency of all dummy variables in r


I am a rookie in R. I want to create a frequency table of all dummy variables and I have a data like this

ID Dummy_2008 Dummy_2009 Dummy_2010 Dummy_2011 Dummy_2012 Dummy_2013
1  1          1          0          0          1          1
2  0          0          1          1          0          1
3  0          0          1          0          0          1
4  0          1          1          0          0          1
5  0          0          0          0          1          0
6  0          0          0          1          0          0

I want to see how total frequency in each variable like this

            0    1   sum
Dummy_2008  5    1   6
Dummy_2009  4    2   6
Dummy_2010  3    3   6
Dummy_2011  4    2   6
Dummy_2012  4    2   6
Dummy_2013  2    4   6

I only know to use table() , but I can only do this one variable a time. I have many time serious dummy variables, and I want to see the trend of them.

Many thanks for the help Terence


Solution

  • Here is another option using mtabulate and addmargins

    library(qdapTools)
    addmargins(as.matrix(mtabulate(df1[-1])),2)
    #           0 1 Sum
    #Dummy_2008 5 1   6
    #Dummy_2009 4 2   6
    #Dummy_2010 3 3   6
    #Dummy_2011 4 2   6
    #Dummy_2012 4 2   6
    #Dummy_2013 2 4   6