【问题标题】:Assign value from another data frame if partially matched: `join` with intern string match如果部分匹配,则从另一个数据框中分配值:`join` 与实习字符串匹配
【发布时间】:2021-08-24 16:01:35
【问题描述】:

我有两个数据框。一个包含参考值。另一个包含长字符串。

library(tidyverse)
ref <- tibble(text  = c("hello",                 "how are you", "example"),
              value = c(1,                       2,             3        ))
df  <- tibble(text  = c("hello my name is john", "how are you", "some other example"))

我想将values 从ref 分配给df,其中ref$text 出现在df$text 中。

现在,如果我想要完全匹配,这很容易:加入/绑定可以完美地工作:left_join(df, ref, by = "text")。但在这里,它只匹配第二行(相同)并忽略部分匹配。

在某种意义上,我想要left_join()str_detect() 的组合或其他类似grep 的模式匹配。 (虽然,我这里其实不需要正则表达式,只需要匹配*ref$text* == df$text


注意:我很欣赏tidyverse/dplyr 解决方案,但base R 当然也可以。

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    在这种情况下,我们可以使用来自fuzzyjoin 包的fuzzy_left_join

    library(fuzzyjoin)
    library(stringr)
    fuzzy_left_join(df, ref, match_fun = str_detect, by = c(text = "text"))
    
      text.x                text.y      value
      <chr>                 <chr>       <dbl>
    1 hello my name is john hello           1
    2 how are you           how are you     2
    3 some other example    example         3
    > df
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-23
      • 2020-11-25
      • 1970-01-01
      • 2013-06-04
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多