首页 > 解决方案 > R中的grep搜索

问题描述

我附上了表格的图像,我想根据以下搜索条件过滤“标题”列。标题列包含文本。

word=c('COVID','coronavirus disease 19','SARS-CoV-2','2019-nCoV','nCoV','coronavirus','wuhan pneumonia','Wuhan')

搜索一个我知道我可以使用的词

merged[grep("COVID",merged$Title),"Title"] 或者

sapply(words, grepl, merged$Title) returns TRUE and FALSE. How to select the rows for which sapply is true.

在此处输入图像描述

标签: r

解决方案


我们可以使用它lapplyReduce它到一个单一的逻辑vector|来子集“合并”的行,即当任何“单词”出现在“标题”列中时,我们正在选择“合并”的行

merged[Reduce(`|`, lapply(words, grepl, merged$Title)),]

另一种选择是将其作为分隔符paste的单个字符串,其作用类似于|OR

pat <- paste0("\\b(", paste(words, collapse="|"), ")\\b")
merged[grepl(pat, merged$Title),]

推荐阅读