2014-10-20 46 views
1

幾天以前我遇到以下data.table發行約值分配:基於前者的電流值從一個data.table替換爲另一個DT的最有效值?

  • 從另一個 data.table柱重新分配列的值(例如DT1$type)(例如DT2$description) (例如DT1$type == DT2$id)。

我解決它以經典的方式(即使用for環),但我注意到,它需要大量的時間的data.table長度的增加。

因此,我想知道是否有更有效的方式來獲得相同的結果?

我的解決辦法:

# Define the sample data.tables 
DT1 <- data.table(user = c(rep(1,2), rep(2,3), rep(3,3)), 
        type = c(1,2,1,4,2,3)) 

DT2 <- data.table(id = 1:4, 
        description = c("aa", "bb", "cc", "dd")) 

# set the keys 
setkeyv(DT1,"user") 
setkeyv(DT2, c("id","description")) 

# Replace values 
for (i in 1:length(DT1$type)) { 
    DT1$type[i] <- DT2[ DT2$id == DT1$type[i], description ] 
} 

回答

2

你必須設置你想要加入的列鍵,然後用[ data.table操作。例如:

DT1 <- data.table(user = c(rep(1,2), rep(2,3), rep(3,3)), 
       type = c(1,2,1,4,2,3)) 
    DT2 <- data.table(id = 1:4, 
       description = c("aa", "bb", "cc", "dd")) 
    setkeyv(DT1,"type") 
    setkeyv(DT2,"id") 
    res<-DT1[DT2,] 
    #drop the first column 
    res[,type:=NULL] 
+0

謝謝,這工作完美,超級快 – bcdp5 2014-10-21 11:45:48