在聚合期间保持空因子级别

时间:2014-06-17 14:12:25

标签: r data.table

我正在使用data.table来聚合值,但是我发现当“by”变量的聚合中没有一个级别时,它会被省略,即使它是在因子级别中指定的。 / p>

下面的代码生成一个包含6行的data.table,其中最后两行只有f1嵌套在f1中的两个可能级别之一。在聚合期间,{3,1}组合被删除。

set.seed(1987)
dt <- 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")=<externalptr> 

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 # <- the missing row from above
6:  3  2 1.3495996

有没有办法实现这种行为?

1 个答案:

答案 0 :(得分:1)

为什么你期望data.table计算f1和f2的所有组合的总和?

如果您想要这样,您应该在分组总和之前将缺失行添加到原始数据。例如:

setkey(dt, f1, f2)
# omit "by = .EACHI" in data.table <= 1.9.2
dt[CJ(levels(f1), levels(f2)), sum(val, na.rm=T),
   allow.cartesian = T, by = .EACHI]
##     f1 f2        V1
## 1:  1  1 0.3829077
## 2:  1  2 0.2327311
## 3:  2  1 0.3456710
## 4:  2  2 0.5965087
## 5:  3  1 0.0000000   ## <- your "missing row" :)
## 6:  3  2 1.3495996
相关问题