R data.table aggregate function using setdiff

Viewed 13

I have a data.table with three columns, and need to do a complex aggregation:

> c
                sample     group  symbol
   1:        APPL/S Up  CBEbrown   Icosl
   2:        APPL/S Up  CBEbrown   Ampd3
   3:        APPL/S Up  CBEbrown   Thbs2
   4:        APPL/S Up  CBEbrown  Map4k4
   5:        APPL/S Up  CBEbrown Slc45a3
  ---
1724: APPL/S_BD10-2 Up TCXyellow   Nfxl1
1725: APPL/S_BD10-2 Up TCXyellow    Rhog
1726: APPL/S_BD10-2 Up TCXyellow   Wipf1
1727: APPL/S_BD10-2 Up TCXyellow Selenos
1728: APPL/S_BD10-2 Up TCXyellow  Kdelr2

so sample has two outcomes, and for each there are 7 groups. Basically, want the fsetdiff of symbols that are in "APPL/S_BD10-2 Up" and not "APPL/S Up":

setdiff(c[group == "TCXyellow" & sample == "APPL/S_BD10-2 Up", symbol], 
        c[group == "TCXyellow" & sample == "APPL/S Up", symbol])

But I want to then count for each symbol, how many groups that fsetdiff occurs (from 0-7 possible). The output would look like:

> out = c[, N_diff := fsetdiff(?????), by="symbol"]
> out
      symbol  N_diff
  1:   Icosl       4
  2:   Ampd3       5
  3:   Thbs2       7
  4:  Map4k4       4
  5: Slc45a3       4
 ---
503:  Unc13d       1
504:   Rpl30       1
505:    Tpt1       1
506:  Garre1       1
507: Selenos       1

Where Icosl is in "APPL/S_BD10-2 Up" and not in "APPL/S Up" for 4 of the 7 groups.

1 Answers

I think you can do something straighforward like this:

f <- function(sam,sym) setdiff(sym[sam!="APPL/S UP"], sym[sam=="APPL/S UP"])

df[,.(symbol = f(sample,symbol)),group][, .(N_diff = uniqueN(group)),symbol]
Related