2013-07-09 24 views
7

我使用data.table(1.8.9)和:=運算符來更新另一個表中的值。要更新的表(dt1)具有許多因子列,並且具有更新(dt2)的表具有類似的列,其值可能不在另一個表中。如果dt2中的列是字符,我會得到一條錯誤消息,但是當我將它們因式分解時,我會得到不正確的值。涉及因素的data.table分配

如何在不將所有因子先轉換爲字符的情況下更新表格?

下面是一個簡化的例子:

library(data.table) 

set.seed(3957) 

## Create some sample data 
## Note column y is a factor 
dt1<-data.table(x=1:10,y=factor(sample(letters,10))) 
dt1 

##  x y 
## 1: 1 m 
## 2: 2 z 
## 3: 3 t 
## 4: 4 b 
## 5: 5 l 
## 6: 6 a 
## 7: 7 s 
## 8: 8 y 
## 9: 9 q 
## 10: 10 i 

setkey(dt1,x) 

set.seed(9068) 

## Create a second table that will be used to update the first one. 
## Note column y is not a factor 
dt2<-data.table(x=sample(1:10,5),y=sample(letters,5)) 
dt2 

## x y 
## 1: 2 q 
## 2: 7 k 
## 3: 3 u 
## 4: 6 n 
## 5: 8 t 

## Join the first and second tables on x and attempt to update column y 
## where there is a match 
dt1[dt2,y:=i.y] 

## Error in `[.data.table`(dt1, dt2, `:=`(y, i.y)) : 
## Type of RHS ('character') must match LHS ('integer'). To check and 
## coerce would impact performance too much for the fastest cases. Either 
## change the type of the target column, or coerce the RHS of := yourself 
## (e.g. by using 1L instead of 1) 

## Create a third table that is the same as the second, except y 
## is also a factor 
dt3<-copy(dt2)[,y:=factor(y)] 

## Join the first and third tables on x and attempt to update column y 
## where there is a match 
dt1[dt3,y:=i.y] 
dt1 

##  x y 
## 1: 1 m 
## 2: 2 i 
## 3: 3 m 
## 4: 4 b 
## 5: 5 l 
## 6: 6 b 
## 7: 7 a 
## 8: 8 l 
## 9: 9 q 
## 10: 10 i 

## No error message this time, but it is using the levels and not the labels 
## from dt3. For example, row 2 should be q but it is i. 

頁的data.table help file 3表示:

當LHS是一個因素柱和RHS與物品 從因子水平缺少字符向量,與基本方法不同,新的級別自動添加(通過引用,有效地) 。

這使得它看起來像我試過應該工作,但顯然我失去了一些東西。我不知道這是否與此相關的類似的問題:

rbindlist two data.tables where one has factor and other has character type for a column

+0

現在看來這是不可能的。 – kohske

回答

1

這裏有一個解決方法:

dt1[dt2, z := i.y][!is.na(z), y := z][, z := NULL] 

注意z是一個字符列和第二次分配正常工作,不知道爲什麼OP一個沒有。

+0

非常感謝解決方法,@ eddi。我不會回答這個問題,希望有人能夠提出爲什麼標準語法看起來不起作用。 – dnlbrky