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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With