Let’s see a minimal example:
library(data.table)
DT = data.table(x=factor(rep(c("b","a","c"),each=3)))
DT[x!="c"][, .N, by = x]
x N
<fctr> <int>
1: b 3
2: a 3
In this example, as x is a factor with 3 levels a,b,c, I would like the output was
x N
<fctr> <int>
1: b 3
2: a 3
3: c 0
or having some argument to control this. Is there some way to get this output?
Thanks!
>Solution :
Using the join syntax
DT[x != "c"][levels(x), on = "x", .N, by = .EACHI]
# x N
# <char> <int>
# 1: a 3
# 2: b 3
# 3: c 0