Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dont drop empty levels with by=2 col in data.table

Tags:

r

data.table

I need show all levels like this:

require(data.table)
x <- data.table(x=runif(3), group=factor(c('a','b','a'), 
  levels=c('a','b','c')),group2=factor(c('u','f','l')))

data.frame(xtabs(~group+group2,x))

 group group2 Freq
     a      f    0
     b      f    1
     c      f    0
     a      l    1
     b      l    0
     c      l    0
     a      u    1
     b      u    0
     c      u    0

There's an elegant way to get the same results with data.table structure? I tried this:

x[,.N,list(group,group2)]

   group group2 N
1:     a      u 1
2:     a      l 1
3:     b      f 1

But doesnt work. Some ideas? Thanks in advance

like image 955
Diego Avatar asked Dec 30 '25 01:12

Diego


1 Answers

If you key by the two columns you wish to group by, you can then use the levels to create all combinations in CJ.

setkeyv(x, c('group','group2'))
x[CJ(levels(group),levels(group2)), .N]

#    group group2 N
# 1:     a      f 0
# 2:     a      l 1
# 3:     a      u 1
# 4:     b      f 1
# 5:     b      l 0
# 6:     b      u 0
# 7:     c      f 0
# 8:     c      l 0
# 9:     c      u 0
like image 149
mnel Avatar answered Jan 01 '26 14:01

mnel