【问题标题】:test if words are in a string (grepl, fuzzyjoin?)测试单词是否在字符串中(grepl、fuzzyjoin?)
【发布时间】:2021-06-07 13:58:32
【问题描述】:

如果一个数据帧的两列的字符串包含在第二个数据帧的一列的字符串中,我需要对两个数据帧进行匹配和连接。

示例数据框:

First <- c("john", "jane", "jimmy", "jerry", "matt", "tom", "peter", "leah")
Last  <- c("smith", "doe", "mcgee", "bishop", "gibbs", "dinnozo", "lane", "palmer")
Name  <- c("mr john smith","", "timothy t mcgee", "dinnozo tom", "jane  l doe", "jimmy mcgee", "leah elizabeth arthur palmer and co", "jerry bishop the cat")
ID    <- c("ID1", "ID2", "ID3", "ID4", "ID5", "ID6", "ID7", "ID8")

df1 <- data.frame(First, Last)
df2 <- data.frame(Name, ID)

所以基本上,我有df1,其中的名字和姓氏相当有序;我有df2,它的名称可以组织为“名字,姓氏”或“姓氏名字”或“名字 MI 姓氏”或其他完全包含名称的东西。我需要来自df2ID 列。所以我想运行一个代码来查看df1$First df2$Last 是否在df2$Name 的字符串中的某个位置,如果是,则将其拉入并加入df2$IDdf1 .

我的 R 大师告诉我使用 fuzzyjoin 包中的 fuzzy_left_join

fzjoin <- fuzzy_left_join(df1, df2, by = c("First" = "Name"), match_fun = "contains")

但它给了我一个错误,即论点不合逻辑;而且我不知道如何重写它来做我想做的事; documentationmatch_fun 应该是 TRUEFALSE,但我不知道该怎么做。此外,它只匹配df1$First 而不是df1$Firstdf1$Last。我想我可能可以使用grepl,但根据我看到的示例不确定如何使用。有什么建议吗?

【问题讨论】:

    标签: r grepl fuzzyjoin


    【解决方案1】:

    文档说match_fun 应该是一个 “给定两列的向量化函数,返回 TRUEFALSE 是否匹配。” 这不是 TRUE 或 FALSE,这是一个返回TRUEFALSE 的函数。如果我们切换您的订单,我们可以使用stringr::str_detect,它会根据需要返回TRUEFALSE

    fuzzyjoin::fuzzy_left_join(
      df2, df1,
      by = c("Name" = "First", "Name" = "Last"),
      match_fun = stringr::str_detect
    )
    #                                  Name  ID First    Last
    # 1                       mr john smith ID1  john   smith
    # 2                                     ID2  <NA>    <NA>
    # 3                     timothy t mcgee ID3  <NA>    <NA>
    # 4                         dinnozo tom ID4   tom dinnozo
    # 5                         jane  l doe ID5  jane     doe
    # 6                         jimmy mcgee ID6 jimmy   mcgee
    # 7 leah elizabeth arthur palmer and co ID7  leah  palmer
    # 8                jerry bishop the cat ID8 jerry  bishop
    

    【讨论】:

    • 我想你的意思是by = c("Name" = "First", "Name" = "Last") ;)
    • 您好,感谢您的帮助!我收到此警告: stri_detect_regex(string, pattern, negate = negate, opts_regex = opts(pattern)) 中的错误:regexp 模式中的语法错误。 (U_REGEX_RULE_SYNTAX, context=CHURCH???) 另外:有50个或更多的警告(使用warnings()查看前50个);有什么建议吗?
    • 嗯,听起来您的某些模式可能包含正则表达式特殊字符。而不是stringr::str_detect,请尝试stringi::stri_detect_fixed。 “固定”模式将特殊字符(如问号)视为文字。
    猜你喜欢
    • 2021-03-15
    • 2012-04-25
    • 2020-05-07
    • 2012-02-25
    • 2011-07-16
    • 1970-01-01
    相关资源
    最近更新 更多