r - 如何在数据框其他列的一列中搜索字符串

标签 r string dataframe string-matching grepl

我有一个表,叫它df,有3列,第一个是产品的标题,第二个是产品的描述,第三个是一个单词串。我需要做的是在整个表上运行一个操作,创建 2 个新列(称它们为“exists_in_title”和“exists_in_description”),它们有一个 1 或 0,指示第三列是否存在于第一列或第二列中。我需要它只是一个 1:1 操作,例如,调用第 1 行“A”,我需要检查单元格 A3 是否存在于 A1 中,并使用该数据创建列
存在_in_title,然后检查A3 是否存在于A2 中,并使用该数据创建列exists_in_description。然后移动到 B 行并执行相同的操作。我有数千行数据,因此一次以 1 个方式执行这些数据是不现实的,为每一行编写单独的函数,绝对需要一个函数或方法,可以一次性遍历表中的每一行。

我玩过 grepl、pmatch、str_count,但似乎没有一个能真正满足我的需求。我认为 grepl 可能是最接近我需要的,这是我编写的 2 行代码的示例,它们在逻辑上按照我希望的方式执行,但似乎不起作用:

df$exists_in_title <- grepl(df$A3, df$A1)

df$exists_in_description <- grepl(df$A3, df$A2)

但是,当我运行它们时,我收到以下消息,这使我相信它无法正常工作:“参数‘模式’的长度 > 1,并且只会使用第一个元素”

任何有关如何做到这一点的帮助将不胜感激。谢谢!

最佳答案

grepl将与 mapply 一起使用:

示例数据框:

title <- c('eggs and bacon','sausage biscuit','pancakes')
description <- c('scrambled eggs and thickcut bacon','homemade biscuit with breakfast pattie', 'stack of sourdough pancakes')
keyword <- c('bacon','sausage','sourdough')
df <- data.frame(title, description, keyword, stringsAsFactors=FALSE)

使用 grepl 搜索匹配项:
df$exists_in_title <- mapply(grepl, pattern=df$keyword, x=df$title)
df$exists_in_description <- mapply(grepl, pattern=df$keyword, x=df$description)

结果:
            title                            description   keyword exists_in_title exists_in_description
1  eggs and bacon      scrambled eggs and thickcut bacon     bacon            TRUE                  TRUE
2 sausage biscuit homemade biscuit with breakfast pattie   sausage            TRUE                 FALSE
3        pancakes            stack of sourdough pancakes sourdough           FALSE                  TRUE

更新我

您也可以使用 dplyr 来执行此操作和 stringr :
library(dplyr)
df %>% 
  rowwise() %>% 
  mutate(exists_in_title = grepl(keyword, title),
         exists_in_description = grepl(keyword, description))

library(stringr)
df %>% 
  rowwise() %>% 
  mutate(exists_in_title = str_detect(title, keyword),
         exists_in_description = str_detect(description, keyword))   

更新二
Map也是一种选择,或者使用更多来自 tidyverse另一种选择可能是 purrrstringr :
library(tidyverse)
df %>%
  mutate(exists_in_title = unlist(Map(function(x, y) grepl(x, y), keyword, title))) %>% 
  mutate(exists_in_description = map2_lgl(description, keyword,  str_detect))

关于r - 如何在数据框其他列的一列中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30782065/

相关文章:

r - 根据 R 中的多列条件查找百分比

java - 如何以编程方式查找字符串中的特定字符

java - 从 Java 字符串中删除 ✅、🔥、✈、♛ 和其他此类表情符号/图像/标志

regex - Word 不以数字或星号和数字开头(正则表达式)

regex - 用r中的条件替换数据框中的部分字符串

python - 将复杂的 str 更改为 pandas Dataframe 中的 float

Python - 如果两列为 NaN,则删除行

r - 如何在数据框中按名称删除列

python - 从字典列表创建 Dataframe,不使用 pd.concat()

r - 在 Shiny 中显示 htmlTable