【问题标题】:Using grep to match variables in one column to a string of text in another column [duplicate]使用 grep 将一列中的变量与另一列中的文本字符串匹配 [重复]
【发布时间】:2021-10-21 18:02:21
【问题描述】:

我需要将第一个变量中的字符串与第二个变量中的字符串进行匹配,然后在第三列中返回 true 或 false。

这是我的数据

regex <- c("cat", "dog", "mouse") 
text<- c("asdf.cat/asdf", "asdf=asdf", "asdf=mouse asdf")
df <- data.frame(regex, text)```

我需要这样的输出

regex text result
cat asdf.cat/asdf 1
dog asdf=asdf 0
mouse asdf=mouse asdf 1

我尝试过使用 grepl,但不知道如何在数据框中使用它。

df$result <- as.integer(grepl("cat", df$text))

这仅适用于第一行

我还尝试了以下代码来过滤掉匹配项,但我想将它们全部保留并只返回 true 或 false。

df %>%
  filter(unlist(Map(function(x, y) grepl(x, y), regex, text)))

如你所见,包含各种字符的文本字符串很复杂

我觉得这应该很容易,但我无法绕开它!

【问题讨论】:

    标签: r grep


    【解决方案1】:

    使用 str_detect 代替 grepl,它是为 patternstring 向量化的

    library(stringr)
    library(dplyr)
    df %>%
        mutate(result= +(str_detect(text, regex)))
    

    -输出

       regex            text result
    1   cat   asdf.cat/asdf      1
    2   dog       asdf=asdf      0
    3 mouse asdf=mouse asdf      1
    

    数据

    df <- structure(list(regex = c("cat", "dog", "mouse"), text = c("asdf.cat/asdf", 
    "asdf=asdf", "asdf=mouse asdf")), class = "data.frame", row.names = c(NA, 
    -3L))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      相关资源
      最近更新 更多