You could set the key
and then do a crossjoin using CJ
in the i
like so...
setkey( dat , var2 , var3 )
# Thanks to @Shadow for pointing out to use unique() in the cross join
dat[ CJ( unique(var2) , unique(var3) ) , mean(var1) ]
# var2 var3 V1
#1: a 1 -0.25771923
#2: a 2 0.04143057
#3: a 3 0.28878451
#4: b 1 0.18865887
#5: b 2 0.53632552
#6: b 3 NA
#7: c 1 NA
#8: c 2 0.38015021
#9: c 3 0.49809159
And by way of explanation, CJ()
creates a data.table
in the i
of x
(in this case dat
) to join on. It is formed as the cross product of the vectors supplied to CJ()
, which happens to be precisely what you are looking for!