2014-06-17 19 views
1

我正在使用data.table來彙總值,但我發現當「by」變量具有不存在於彙總中的級別時,即使它被指定,它也被省略在因素水平。彙總期間保留空因子水平

下面的代碼用6行生成一個data.table,最後兩個只有嵌套在f1內的f2的兩個可能級別之一。在彙總過程中,{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

爲什麼你期望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 
+0

我預計這種行爲是因爲我在其他函數中看到過它。例如:'table(dt $ f1,dt $ f2)'產生所有組合的結果。 –