如何从 R 中的 stringr::str_detect 中提取匹配项到列表向量中

How to extract matches from stringr::str_detect in R into a list vector

我正在尝试对文本数据库执行以下搜索。

这里是示例数据库,df

df <- data.frame(

  id = c(1, 2, 3, 4, 5, 6), 
  name = c("john doe", "carol jones", "jimmy smith", 
           "jenny ruiz", "joey jones", "tim brown"), 
  place = c("reno nevada", "poland maine", "warsaw poland", 
           "trenton new jersey", "brooklyn new york", "atlanta georgia")

  )

我有一个字符串向量,其中包含我要查找的术语。

new_search <- c("poland", "jones")

我将向量传递给 str_detect 以在 df 的任何列中找到 new_search 中的任何字符串,然后 return 匹配的行...

df %>% 
    filter_all(any_vars(str_detect(., paste(new_search, collapse = "|")))) 

问题...如何将 str_detect 的结果提取到新列中?
对于 returned 的每一行...我想生成一个成功匹配的术语列表,并将它们放入列表或字符向量 (matched_terms)...类似这样...

  id        name             place    matched_terms   
1  2 carol jones      poland maine   c("jones", "poland")
2  3 jimmy smith     warsaw poland   c("poland")
3  5  joey jones brooklyn new york   c("jones")


      

您可以使用str_extract_all提取多列中的所有模式,使用unite将它们组合成一列。 unite 将列合并为一个字符串,因此空值会变成 "character(0)",我们使用 str_remove_all 将其删除,并仅保留那些具有任何匹配项的行。

library(tidyverse)

pat <- str_c(new_search, collapse = "|")

df %>%
  mutate(across(-id, ~str_extract_all(., pat), .names = '{col}_new')) %>% 
  unite(matched_terms, ends_with('new'), sep = ',') %>%
  mutate(matched_terms = str_remove_all(matched_terms, 
                         'character\(0\),?|,character\(0\)')) %>%
  filter(matched_terms != '')

#  id        name             place matched_terms
#1  2 carol jones      poland maine  jones,poland
#2  3 jimmy smith     warsaw poland        poland
#3  5  joey jones brooklyn new york         jones

这是我天真的解决方案:

new_search <- c("poland", "jones") %>% paste(collapse = "|")
df %>% 
  mutate(new_var = str_extract_all(paste(name, place), new_search))