【问题标题】:Merging two data frames using Fuzzy Merge使用模糊合并合并两个数据帧
【发布时间】:2017-12-17 16:56:07
【问题描述】:

我有两个必须合并的数据框。两个数据框中都有一列,我想在其上合并两个数据框。但是这两列的数据并不相似。这两个数据帧中的键列长度为12位,另外一个为5 -6位。我想根据第二个数据帧中相似的 5-6 位进行合并。

我的数据框:

df1 = data.frame(CustomerId = c(987689000000,786581000000,765909000000,565400000000,746541000000,516890000000), Product = c(rep("Toaster", 3), rep("Radio", 3)))   

df2 = data.frame(customerId = c(987689,986581,7659090,56540,74651,5168900), State = c(rep("Alabama", 2), rep("Ohio", 1)))

我试过c = merge(df1,df2 , key =("CustomerId "),all = TRUE)

我的预期输出如下:-

  CustomerId  Product    State
1  987689     Toaster     Alabama
2  786581     Toaster      Alabama
3  7659090    Toaster      Alabama
4  56540       Radio      Alabama
5  74651       Radio      Alabama
6  516890     Radio        Alabama

【问题讨论】:

    标签: r merge


    【解决方案1】:

    这里有一个解决方案。关键是用formatC调整数字格式,用str_extract提取匹配的部分。在这一步之后,您可以确定是否要使用left_join、right_join 或inner_join 来保留数据帧的哪一部分。 df3 是最终输出。

    请注意,您提供的示例包含不匹配的 ID,因此根据您提供的数据框,无法重现您想要的输出。

    # Load packages
    library(dplyr)
    library(stringr)
    library(rebus)
    
    # Process the data
    df3 <- df1 %>%
      # Use str_extract to get CustomerId matched in df2
      mutate(CustomerId = str_extract(string = formatC(CustomerId, 
                                                       digits = 0, 
                                                       format = "f"), 
                                      pattern = or1(df2$customerId))) %>%
      # Join with df2 by the updated CustomerId
      right_join(df2 %>% 
                   mutate(CustomerId = as.character(customerId)) %>%
                   select(-customerId), 
                by = "CustomerId")
    
    # View the result
    df3
    #  CustomerId Product   State
    #1     987689 Toaster Alabama
    #2     986581    <NA> Alabama
    #3    7659090 Toaster    Ohio
    #4      56540   Radio Alabama
    #5      74651    <NA> Alabama
    #6    5168900   Radio    Ohio
    

    【讨论】:

    • 我很乐意提供帮助。如果这个答案有帮助,请点击左上角的绿色标记接受它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 2014-04-14
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2011-01-14
    • 2019-03-29
    相关资源
    最近更新 更多