Keep Empty Factor Levels During Aggregation <p>I'm using data.table to aggregate values, but I'm finding that when the "by" variable has a level not present in the aggregation, it is omitted, even if it is specified in the factor levels.</p> <p>The code below generates a data.table with 6 rows, the last two of which only have one of the two possible levels for f2 nested within f1. During aggregation, the {3,1} combination is dropped.</p> <pre><code>set.seed(1987) dt &lt;- data.table(f1 = factor(rep(1:3, each = 2)), f2 = factor(sample(1:2, 6, replace = TRUE)), val = runif(6)) str(dt) Classes ‘data.table’ and 'data.frame': 6 obs. of 3 variables: $ f1 : Factor w/ 3 levels "1","2","3": 1 1 2 2 3 3 $ f2 : Factor w/ 2 levels "1","2": 1 2 2 1 2 2 $ val: num 0.383 0.233 0.597 0.346 0.606 ... - attr(*, ".internal.selfref")=&lt;externalptr&gt; dt f1 f2 val 1: 1 1 0.3829077 2: 1 2 0.2327311 3: 2 2 0.5965087 4: 2 1 0.3456710 5: 3 2 0.6058819 6: 3 2 0.7437177 dt[, sum(val), by = list(f1, f2)] # output is missing a row f1 f2 V1 1: 1 1 0.3829077 2: 1 2 0.2327311 3: 2 2 0.5965087 4: 2 1 0.3456710 5: 3 2 1.3495996 # this is the output I'm looking for: f1 f2 V1 1: 1 1 0.3829077 2: 1 2 0.2327311 3: 2 2 0.5965087 4: 2 1 0.3456710 5: 3 1 0.0000000 # &lt;- the missing row from above 6: 3 2 1.3495996 </code></pre> <p>Is there a way to achieve this behavior?</p>