【问题标题】:R data.table add new column with query for each rowR data.table 为每一行添加带有查询的新列
【发布时间】:2017-12-13 01:00:58
【问题描述】:

我在 R 中有 2 个 R data.tables,如下所示:

first_table

id | first | trunc | val1
=========================
 1 |   Bob | Smith |   10
 2 |   Sue | Goldm |   20
 3 |   Sue | Wollw |   30
 4 |   Bob | Bellb |   40

second_table

id | first |       last | val2
==============================
 1 |   Bob |      Smith |    A
 2 |   Bob |      Smith |    B
 3 |   Sue |    Goldman |    A
 4 |   Sue |    Goldman |    B
 5 |   Sue |  Wollworth |    A
 6 |   Sue |  Wollworth |    B
 7 |   Bob | Bellbottom |    A
 8 |   Bob | Bellbottom |    B

如您所见,第一个表中的姓氏被截断。此外,名字和姓氏的组合在第一个表中是唯一的,但在第二个表中不是。我想在令人难以置信的幼稚假设下“加入”名字和姓氏的组合

  • first,last 唯一地定义一个人
  • 截断姓氏不会引起歧义。

结果应该是这样的:

id | first | trunc |       last | val1 
=======================================
 1 |   Bob | Smith |      Smith |   10
 2 |   Sue | Goldm |    Goldman |   20
 3 |   Sue | Wollw |  Wollworth |   30
 4 |   Bob | Bellb | Bellbottom |   40

基本上,对于 table_1 中的每一行,我都需要找到一个回填姓氏的行。

对于 first_table 中的每一行: 在 second_table 中找到第一行: 匹配 first_name & trunc 是 last 的子字符串 然后加入那一行

有没有一种简单的矢量化方法可以使用data.table 完成此操作?

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    一种方法是加入first,然后根据子字符串匹配进行过滤

    first_table[
        unique(second_table[, .(first, last)])
        , on = "first"
        , nomatch = 0
    ][
        substr(last, 1, nchar(trunc)) == trunc
    ]
    
    #    id first trunc val1       last
    # 1:  1   Bob Smith   10      Smith
    # 2:  2   Sue Goldm   20    Goldman
    # 3:  3   Sue Wollw   30  Wollworth
    # 4:  4   Bob Bellb   40 Bellbottom
    

    或者,对second_table 进行截断以匹配第一列,然后在两列上加入

    first_table[
        unique(second_table[, .(first, last, trunc = substr(last, 1, 5))])
        , on = c("first", "trunc")
        , nomatch = 0
    ]
    ## yields the same answer
    

    【讨论】:

      猜你喜欢
      • 2022-07-27
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2018-04-07
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多