【问题标题】:R: Combining dataset and lookup-table to extract value to new columeR:结合数据集和查找表以将值提取到新卷
【发布时间】:2020-05-12 08:50:47
【问题描述】:

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

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

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

【问题讨论】:

    标签: r dataframe matching


    【解决方案1】:

    我们可以在data.table中使用join

    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"))
    

    【讨论】:

    • 适用于您的代码,但不适用于我自己的数据框。已更改列名,仍然得到:“参数指定列指定不存在的列:cols[1]='col1'”或“不兼容的连接类型:x.col1(字符)和 i.c1(双)”。最后一个我用 structure(list(col1 = df1$col1 ....) 解决了。有什么想法吗?
    • @Fjellbekken 我认为您的列类型不同。您可以更改df1$col1 &lt;- as.numeric(df1$col1) 或更改df2$c1 &lt;- as.character(df2$c1)
    猜你喜欢
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 2019-04-09
    • 2020-05-20
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    相关资源
    最近更新 更多