R data.table替换多列中的值

Ant*_*n84 3 r data.table

我是R的新手,也是stackoverflow的新手.我试图弄清楚data.table并查看"R data.table替换另一个data.table的值索引"并认为我理解但无法得到我想要的东西.

我有两个数据框 - 第一个是我感兴趣的数据,第二个是包含名称/ ID的键,用于转换第一个数据框中的ID.我想使用"key"data.table将表$ id1和table $ 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)]
Run Code Online (Sandbox Code Playgroud)

我已经得到了这个(表$ id1中的名称的替换值),但无法弄清楚如何在不更改列名的情况下更改id2,重置键并重新执行上述id2的相同步骤.在真实数据集中,将有多个Sally,John等,我希望代码使用相同的密钥"翻译"两列.

希望代码使用data.table(用于学习目的)但是如果有另一个包可以做得更好,那也会很棒.谢谢!

Sym*_*xAU 5

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
Run Code Online (Sandbox Code Playgroud)

数据

## 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))
Run Code Online (Sandbox Code Playgroud)