R: Fastest way to sum the number of observations for multiple variables

I'm sure this is a very simple thing, but I can't seem to find a really quick and easy solution.

I have a patient data with a lot of columns in the following format:

patID   disease   category ...
1       1          A
2       0          B
3       1          C
4       1          B

      

How can I quickly create a pivot table that includes the number of observations for each column / variable in the dataframe? The result should be something like this:

VARIABLE     Number of rows
disease:1    3
disease:0    1
category:A   1
category:B   2
category:C   1
...

      

I know I can do this for one variable just by using a table ($ data column). But how can I create something like this for all columns in a dataframe?

+3


source to share


1 answer


Using tidyr

and dplyr

:

gather(data, variable, value, -patID) %>%
  count(variable, value)

      



(Thanks @Frank for the reminder of tally

and count

.)

+7


source







All Articles