【问题标题】:R: Regex_Join/Fuzzy_Join - Join Inexact Strings in Different Word OrdersR:Regex_Join/Fuzzy_Join - 以不同的词序加入不精确的字符串
【发布时间】:2019-06-02 10:07:16
【问题描述】:

df1

df2

df3

library(dplyr)
library(fuzzyjoin)
df1  <- tibble(a =c("Apple Pear Orange", "Sock Shoe Hat", "Cat Mouse Dog"))
df2  <- tibble(b =c("Kiwi Lemon Apple", "Shirt Sock Glove", "Mouse Dog"),
               c = c("Fruit", "Clothes", "Animals"))
# Appends 'Animals'
df3 <-  regex_left_join(df1,df2, c("a" = "b"))
# Appends Nothing
df3 <-  stringdist_left_join(df1, df2,  by = c("a" = "b"), max_dist = 3, method = "lcs")

我想使用字符串将 df2 的 c 列附加到 df1, “苹果”、“袜子”和“老鼠狗”。

我尝试使用 regex_joinfuzzyjoin 执行此操作,但字符串的顺序似乎很重要,而且似乎找不到解决方法。

【问题讨论】:

    标签: r regex string-matching fuzzyjoin


    【解决方案1】:

    regex_left_join 有效,但它不仅仅是在寻找任何相似之处。正如描述中所说,

    通过另一个表中的正则表达式列连接一个带有字符串列的表

    所以,我们需要提供一个正则表达式模式。如果df2$b 包含单独的感兴趣的单词,我们可能会这样做

    (df2$regex <- gsub(" ", "|", df2$b))
    # [1] "Kiwi|Lemon|Apple" "Shirt|Sock|Glove" "Mouse|Dog"      
    

    然后

    regex_left_join(df1, df2, by = c(a = "regex"))[-ncol(df1) - ncol(df2)]
    # A tibble: 3 x 3
    #   a                 b                c      
    #   <chr>             <chr>            <chr>  
    # 1 Apple Pear Orange Kiwi Lemon Apple Fruit  
    # 2 Sock Shoe Hat     Shirt Sock Glove Clothes
    # 3 Cat Mouse Dog     Mouse Dog        Animals
    

    其中-ncol(df1) - ncol(df2) 只是删除包含正则表达式模式的最后一列。

    【讨论】:

    • 谢谢,正要接受。首先是一个简单的问题:我替换了“|”用逗号但它不起作用 - 是 or 运算符允许它工作,是吗?
    • @rsylatian,确实!管道“|”代表正则表达式中的 OR 运算符。所以“Mouse|Dog”的意思是:匹配“Mouse”或“Dog”。由于可以编写正则表达式模式,这确实是一个强大的功能,并且还可以处理更复杂的情况。
    猜你喜欢
    • 2020-06-05
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2019-03-11
    • 2013-09-23
    • 2018-01-21
    • 2020-01-26
    • 2013-01-14
    相关资源
    最近更新 更多