【问题标题】:Partial string match in another dataframe in rr中另一个数据框中的部分字符串匹配
【发布时间】:2020-11-25 00:35:36
【问题描述】:

有没有办法可以找到从 df_2 到 df_1 的所有部分匹配项?

部分匹配(如果 DF_1 字符串的一部分在 DF_2 的整个字符串中) 例如,“for solution”的一部分在“solution”的整个字符串中

df_1=data.frame(
  DF_1=c("suspension","tablet","for solution","capsule")
)

df_2=data.frame(
  index=c("1","2","3","4","5"),
  DF_2=c("for suspension", "suspension", "solution", "tablet,ER","tablet,IR")
)

df_out=data.frame(
  DF_1=c("suspension","suspension","tablet","tablet","for solution"),
  DF_2=c("for suspension", "suspension","tablet,ER","tablet,IR","solution"),
  index=c("1","2","4","5","3")
)

【问题讨论】:

  • 如何定义部分匹配?根据您的示例,是“df_a 中的字符串链完全包含在 df_b 中”吗?
  • 这能回答你的问题吗? Test if characters are in a string
  • @Arault,我在上面定义了部分匹配。如果我在 DF_1 中的部分字符串在 DF_2 中。例如,“解决方案”的一部分在“解决方案”中,所以这是匹配的。
  • @Ashti 在这种情况下,“解决方案”不应该与“暂停”合并吗?两者都有“for”
  • 否,因为“for solution”的一部分在“solution”作为一个整体,而不是“for suspend”作为一个整体字符串。

标签: r dplyr match


【解决方案1】:

我们可以使用fuzzyjoin

library(fuzzyjoin)
regex_left_join(df_2, df_1, by = c("DF_2"= "DF_1"))

【讨论】:

  • 谢谢!这没有返回其中一行的匹配项。
【解决方案2】:

遵循@Akrun 建议使用fuzzyjoin

根据你预期的输出,你想加入两次,你想执行inner_join。 最后,如果存在完美匹配,您将匹配两次,这就是您要删除重复数据的原因(我使用 distinctdplyr 进行了此操作,但您可以根据需要进行操作。

df_out = distinct(
  rbind(
    regex_inner_join(df_1, df_2, by = c("DF_1"= "DF_2")),
    regex_inner_join(df_2, df_1, by = c("DF_2"= "DF_1"))
  )
)
df_out

输出是:

          DF_1 index           DF_2
1   suspension     2     suspension
2 for solution     3       solution
3   suspension     1 for suspension
4       tablet     4      tablet,ER
5       tablet     5      tablet,IR

您会找到预期的表格,但顺序不同(行和列)。

【讨论】:

    【解决方案3】:

    这是一个使用嵌套 *apply + grepl 的基本 R 选项

    df_out <- within(
      df_2,
      DF_1 <- unlist(sapply(
        DF_2,
        function(x) {
          Filter(
            Negate(is.na),
            lapply(
              df_1$DF_1,
              function(y) ifelse(grepl(y, x), y, ifelse(grepl(x, y), x, NA))
            )
          )
        }
      ), use.names = FALSE)
    )
    

    这样

    > df_out
      index           DF_2       DF_1
    1     1 for suspension suspension
    2     2     suspension suspension
    3     3       solution   solution
    4     4      tablet,ER     tablet
    5     5      tablet,IR     tablet
    

    【讨论】:

      【解决方案4】:

      这听起来像是grepl() 的工作!

      例如grepl(value, chars, fixed = TRUE) 让我引用an example from a different answer:

      > chars <- "test"
      > value <- "es"
      > grepl(value, chars)
      [1] TRUE
      > chars <- "test"
      > value <- "et"
      > grepl(value, chars)
      [1] FALSE
      

      【讨论】:

        猜你喜欢
        • 2014-07-20
        • 2020-09-19
        • 1970-01-01
        • 1970-01-01
        • 2018-07-10
        • 2022-01-17
        • 2021-08-11
        • 2018-03-17
        • 1970-01-01
        相关资源
        最近更新 更多