0

How do I draw the sum value of each class represented like the table:

    a    a,b    a,b,c    c
    5     2       1      2

E.g for the above example expected result is:

    a    b    c
    8    3    3

I'm asking this since I couldn't even find a close solution anywhere in the stackoverflow, the closest solution represented was the dcast function, but that only checks for equality, not presence.

Community
  • 1
  • 1
lkn2993
  • 566
  • 7
  • 26
  • Urg, that's ugly, but using `tidyr` and `dplyr`: `dat %>% gather(var, val) %>% separate_rows(var, sep = ',') %>% group_by(var) %>% summarise(val = sum(val)) %>% spread(var, val)` – alistaire Jun 28 '16 at 06:44

1 Answers1

3

One way using base R,

sapply(unique(unlist(strsplit(names(df), '\\.'))), function(i) 
                                  sum(df[grepl(i, names(df))]))
#a b c 
#8 3 3 

Note: I used \\. for strsplit instead of , since names were read like that.

Sotos
  • 51,121
  • 6
  • 32
  • 66