从 R 中的向量中的字符串中检测字符串的摘录

Detect excerpt of string from strings in a vector in R

使用字符串向量(数据框的一列),我试图识别字符串摘录来自哪个字符串。

在下面的示例中,excerpt_of_stringvector_of_strings 中第二个元素的摘录(特别是前 119 个字符):

excerpt_of_string <- "Considering utilizing eLearning days for snow make-up? Join us on 12/8 for Snow day, sNOw problem! Details https://t.co"

vector_of_strings <- c("Meow", 
                       "Considering utilizing eLearning days for snow make-up? Join us on 12/8 for Snow day, sNOw problem! Details https://t.co/LfbPne3uuo #INeLearn", 
                       "Bark")

我首先尝试使用grepl,预计vector_of_strings的第二个元素将是TRUE,但所有元素都是错误的:

grepl(excerpt_of_string, vector_of_strings)
[1] FALSE FALSE FALSE

我还尝试了 stringr 包中的 str_detect

stringr::str_detect(vector_of_strings, excerpt_of_string)
[1] FALSE FALSE FALSE

为什么这些方法无法检测 vector_of_strings 第二个元素中的摘录 excerpt_of_string

由于驻留在您的字符串中的元字符,它未进行检测。

您可以使用 fixed=TRUE 参数将整个字符串模式视为文字。

grepl(excerpt_of_string, vector_of_strings, fixed=TRUE)
# [1] FALSE  TRUE FALSE

\Q ... \E,也可用于忽略模式中的元字符。

grepl(paste0('\Q', excerpt_of_string, '\E'), vector_of_strings)
# [1] FALSE  TRUE FALSE