我是 R 新手,也是 stackoverflow 新手。我试图找出 data.table 并查看“R data.table 替换另一个 data.table 中的值索引”,并认为我理解但无法得到我想要的。
我有两个数据帧 - 第一个是我感兴趣的数据,第二个是包含名称/ID 的键,用于翻译第一个数据帧中的 ID。我想使用“key”data.table 将 table$id1 和 table$id2 中的数字转换为“key”data.table 中的“名称”。这是我到目前为止所做的:
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)]
我已经了解了这么多(用 table$id1 中的名称替换值),但不知道如何在不更改列名称、重置键和对 id2 重复执行上述相同步骤的情况下更改 id2。在真实的数据集中,会有多个 Sally、John 等,我希望代码使用相同的键“翻译”这两列。
希望代码使用 data.table (用于学习目的),但如果有另一个包可以做得更好,那就太好了。谢谢!
在
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))
另一种方法:
dt <- merge(table, key, by.x = c("id1"), by.y = c("id1"), sort = FALSE)
table <- merge(dt, key, by.x = c("id2"), by.y = c("id1"), sort = FALSE)
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