【发布时间】: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)))
如你所见,包含各种字符的文本字符串很复杂
我觉得这应该很容易,但我无法绕开它!
【问题讨论】: