R:结合数据集和 lookup-table 将值提取到新列

R: Combining dataset and lookup-table to extract value to new colume

我想合并数据帧,df1 有 15.000 obs 和 df2 由 2.3 mill 组成。我正在尝试匹配值,如果 df1$col1 == df2$c1,并且 df1$col2 == df2$c2,则将值从 df2$dummy 插入到 df1$col3。如果两者都不匹配,则什么也不做。都是 8 位数字,除了 df2$dummy,它是 0 或 1 的虚拟。

df1  col1       col2      col3
1    25382701   65352617  -
2    22363658   45363783  -
3    20019696   23274747  -
df2  c1         c2        dummy
1    17472802   65548585  1
2    20383829   24747473  0
3    20019696   23274747  0 
4    01382947   21930283  1
5    22123425   65382920  0

在示例中,唯一的匹配项是第 3 行,虚拟列中的值 0 应插入到 col3 row3 中。 我试图查找 table,一个 for 和 if 的函数,但在两个数据帧中需要匹配时没有找到解决方案。 (不用说我猜,但我是 R 和编程的新手..)

我们可以在 data.table

中使用联接
library(data.table)
df1$col3 <- NULL
setDT(df1)[df2, col3 := i.dummy, on = .(col1 = c1, col2 = c2)]
df1
#       col1     col2 col3
#1: 25382701 65352617   NA
#2: 22363658 45363783   NA
#3: 20019696 23274747    0

数据

df1 <- structure(list(col1 = c(25382701L, 22363658L, 20019696L), col2 = c(65352617L, 
45363783L, 23274747L), col3 = c("-", "-", "-")), class = "data.frame", row.names = c("1", 
"2", "3"))

df2 <- structure(list(c1 = c(17472802L, 20383829L, 20019696L, 1382947L, 
22123425L), c2 = c(65548585L, 24747473L, 23274747L, 21930283L, 
65382920L), dummy = c(1L, 0L, 0L, 1L, 0L)), class = "data.frame",
row.names = c("1", 
"2", "3", "4", "5"))