【问题标题】:How to update new column in data-frame with specific column from another data-frame with duplicated in r?如何使用在 r 中重复的另一个数据框中的特定列更新数据框中的新列?
【发布时间】:2020-12-18 23:28:10
【问题描述】:

大家好,我的 df1 看起来像

MNO  DOB
123  NA
123  NA
234  NA
234  NA
345  NA
456  NA
456  NA

我的 df2 有

MNO  DOB
123  22-04-1996
234  16-06-1994
345  05-05-1990
456  18-08-2000

我使用 df3

我得到的输出看起来像

MNO  DOB
123  22-04-1996
123  NA
234  16-06-1994
234  NA
345  05-05-1990
456  18-08-2000
456  NA

预期结果:

MNO  DOB
123  22-04-1996
123  22-04-1996
234  16-06-1994
234  16-06-1994
345  05-05-1990
456  18-08-2000
456  18-08-2000

【问题讨论】:

    标签: r dplyr merge


    【解决方案1】:

    根据显示的示例,列应由同一列“MNO”合并,因此我们可以使用by 而不是by.x

    merge(df1[1], df2, by = "MNO", all.x = TRUE)
    #  MNO        DOB
    #1 123 22-04-1996
    #2 123 22-04-1996
    #3 234 16-06-1994
    #4 234 16-06-1994
    #5 345 05-05-1990
    #6 456 18-08-2000
    #7 456 18-08-2000
    

    如果 'df3' 的输出基于不同的代码,在 merge 步骤之后,我们可以 fill from tidyr 用之前的非 NA 填充 NA 元素

    library(tidyr)
    library(dplyr)
    df3 <- df3 %>%
                 fill(DOB)
    

    【讨论】:

      【解决方案2】:

      使用data.tableroll=T 选项的另一种解决方案:

      merge(dx[,list(MNO)],dx2,roll=TRUE)
      
       MNO        DOB
      1: 123 22-04-1996
      2: 123 22-04-1996
      3: 234 16-06-1994
      4: 234 16-06-1994
      5: 345 05-05-1990
      6: 456 18-08-2000
      7: 456 18-08-2000
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-11
        • 2021-10-04
        • 2019-11-23
        • 2023-01-18
        • 1970-01-01
        相关资源
        最近更新 更多