2016-05-01 157 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))