2016-05-01 166 views
2

我是新來的R和新的stackoverflow。我試圖找出data.table,並看着「R data.table替換另一個data.table的值的索引」,並認爲我明白,但不能得到我想要的。R data.table替換多個列中的值

我有兩個數據框 - 第一個是我感興趣的數據,第二個是包含名稱/ ID的鍵,用於轉換第一個數據框中的ID。我想使用「key」data.table將表$ id1和表$ id2中的數字轉換爲「key」data.table中的「Names」。下面是我到目前爲止管理:

table<-data.table("Sample" = sample(40:46, 6), "Conc1" = sample(100:106,6), 
       "id1" = as.character(sample(1:6, 6)), "Conc2" = sample(200:206,6), 
       "id2" = as.character(sample(1:6, 6))) 

key<-data.table("Name" = c("Sally", "John", "Roger", "Bob", "Kelsey", "Molly"), 
      "id1" = as.character(1:6)) 

setkey(table, id1) 
setkey(key, id1) 

table[key, `:=`(id1 = i.Name)] 

到目前爲止,我已經得到了這個(取代值表$ ID1名),但無法弄清楚如何也改變ID2不改變的列名,重置按鍵並重新爲id2執行上述同樣的步驟。在真實的數據集中,會有多個Sally's,John's等,我希望代碼使用相同的密鑰「翻譯」兩列。

希望代碼使用data.table(用於學習目的),但是如果有另一個包可以做得更好,那也會很棒。謝謝!

回答

0

這樣做的另一種方法:

dt <- merge(table,key,by.x = c('id1'),by.y = c('id1'),sort=F) 

table <- merge(dt,key,by.x = c('id2'),by.y = c('id1'),sort=F) 

table[,id1 := Name.x] 
table[,id2 := Name.y] 
table[,Name.x := NULL] 
table[,Name.y := NULL] 

##  id2 id1 Sample Conc1 Conc2 
##1: Bob Bob  41 101 200 
##2: Kelsey John  46 100 203 
##3: Roger Molly  43 102 206 
##4: Sally Kelsey  42 105 201 
##5: John Roger  44 106 202 
##6: Molly Sally  45 104 204 
4

data.table你不需要設置鍵做加盟。您可以在on=參數中指定連接列。

而且從data.table v1.9.6開始,您可以使用on=參數加入不同的列名稱。

library(data.table) ## v1.9.6 + 

## update id1 based on Name 
table[ key, on = c("id1"), nomatch = 0, id1 := i.Name] 
## here the id1 column is getting updated to i.Name 
## (the 'i.' is the prefix given to columns on the 'right' side of the join). 

## update id2 based on Name 
table[ key, on = c(id2 = "id1"), nomatch = 0, id2 := i.Name] 

table 

# Sample Conc1 id1 Conc2 id2 
#1:  40 100 John 201 John 
#2:  43 101 Kelsey 206 Kelsey 
#3:  45 103 Molly 205 Roger 
#4:  42 102 Roger 204 Bob 
#5:  44 104 Sally 200 Molly 
#6:  41 105 Bob 202 Sally 

數據

## setting seed because we are sampling 
set.seed(1234) 
table<-data.table("Sample" = sample(40:46, 6), "Conc1" = sample(100:106,6), 
        "id1" = as.character(sample(1:6, 6)), "Conc2" = sample(200:206,6), 
        "id2" = as.character(sample(1:6, 6))) 

key<-data.table("Name" = c("Sally", "John", "Roger", "Bob", "Kelsey", "Molly"), 
       "id1" = as.character(1:6))