我有两个数据框,“data”和“scores”,想将它们合并到“id”列上:
data = data.frame(id = c(1,2,3,4,5),
state = c("KS","MN","AL","FL","CA"))
scores = data.frame(id = c(1,1,1,2,2,3,3,3),
score = c(66,75,78,86,85,76,75,90))
merge(data, scores, by = "id")
semi_join(data, scores, by = "id")
在“scores”数据中,有多个观察值的“id”,其中每个匹配在连接之后获得一行。见
?merge
:If there is more than one match, all possible matches contribute one row each.
但是,我只想保留与
scores
中的第一个匹配项对应的行 table 。半连接本来不错,但我无法从正确的表格中选择分数。
有什么建议?
最佳答案
使用 data.table
连同 mult = "first"
和 nomatch = 0L
:
require(data.table)
setDT(scores); setDT(data) # convert to data.tables by reference
scores[data, mult = "first", on = "id", nomatch=0L]
# id score state
# 1: 1 66 KS
# 2: 2 86 MN
# 3: 3 76 AL
对于
data
上的每一行的 id
列,scores
中的匹配行' id
找到列,并保留第一个(因为 mult = "first"
)。如果没有匹配项,它们将被删除(因为 nomatch = 0L
)。
关于r - 合并具有多个匹配项的数据框时仅选择第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37749412/