我正在尝试对文本数据库执行以下搜索。
这是示例数据库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中的任意字符串,然后返回匹配的行。。。
df %>%
filter_all(any_vars(str_detect(., paste(new_search, collapse = "|"))))
问题。。。如何将str_detect的结果提取到一个新列中
对于返回的每一行。。。我想生成一个成功匹配的术语列表,并将它们放在列表或字符向量(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")
这是我天真的解决方案:
new_search <- c("poland", "jones") %>% paste(collapse = "|")
df %>%
mutate(new_var = str_extract_all(paste(name, place), new_search))
您可以使用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