Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

r table for many columns

My dataset is like this.

   ID    Col_01    Col_02   Col_03    Col_04    Col_05    Col_06
   1     1         2        1         3         4         -9
   2     1         1        2         1         2          2
   3     2         4        1         1         1          1
   4     3         1        3         2        -9          4
   5     2         3        4         4         3          2

I like to create a summarized dataset where the number of 1s,2s,3s,4s, -9s in each column (Col_01-Col_06) are counted like this.

    Values    Col_01    Col_02   Col_03    Col_04    Col_05    Col_06   
    1         2         2        2         2         1         1
    2         2         1        1         1         1         2
    3         1         1        1         1         1         0
    4         0         1        1         1         1         1
   -9         0         0        0         0         1         1

So far I tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    df %>%
      select(matches(^Col_\\d+$")) %>%
       summarise_all(funs(table))

but I get an error Col_05 must be of size 4 or 1 , not 5 as earlier column had size 4. and bunch of other warnings. Any suggestions how I can create table summary for all columns starting with Col_ in my dataset is appreciated, Thanks.

>Solution :

In base R you could do

table(stack(df1,-1))

If you need a dataframe:

as.data.frame matrix(table(stack(df1,-1)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading