如何在每一行中使用grepl?

问题描述 投票:3回答:3

我正在尝试使用grepl在文本中搜索模式。问题是我的模式是一个名单列表,我的文本也是一个相同长度的文本列表。我想建立一个遍历每一行并在相应文本中搜索给定名称的循环。

编辑清楚

例如,在这个数据中:

pat <- c("mary", "john", "anthony") 
text <- c("This is a long text about anthony", "This is another long text about john", "This is a final text about mary"). 

我想在第一个文本中搜索"mary",然后在第二个文本中搜索"john",最后在第三个文本中搜索"anthony"

r grep grepl
3个回答
6
投票
pat <- c("mary", "john", "anthony") 
text <- c("This is a long text about anthony", "This is another long text about john", "This is a final text about mary")

Mapmapply函数将执行此操作:

Map(grepl,pat,text) 

(这会返回一个列表,你可以unlist

要么

mapply(grepl,pat,text) 

(自动简化)或

n <- length(pat)
res <- logical(n)
for (i in seq(n)) {
  res[i] <- grepl(pat[i],text[i])
}

4
投票

使用新的样本数据,您可以:

pat <- c("mary", "john", "anthony") 
text <- c("This is a long text about anthony", "This is another long text about john", "This is a final text about mary")

sapply(1:length(pat), function(x) grepl(pat[x],text[x]))

返回:

[1] FALSE  TRUE FALSE

希望这可以帮助。


2
投票

另一种选择是使用Vectorize

Vectorize(grepl)(pattern = pat, x = text, ignore.case = TRUE)
#   mary    john anthony 
#  FALSE    TRUE   FALSE 
© www.soinside.com 2019 - 2024. All rights reserved.