2017-08-01 61 views
2

我正在尝试使用grepl在文本中搜索图案。问题是我的模式是一个名称列表,我的文本也是一个长度相同的文本列表。我想建立一个遍历每一行并在相应文本中搜索给定名称的循环。如何在每一行中使用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"第三个。

+0

尝试'grepl(paste0(PAT,塌陷= “|”),文字,ignore.case = TRUE)'。 – Abdou

+0

谢谢!我以前见过这个答案,它不能解决我的问题。我可以更好地解释自己。我不想在文本中搜索所有的名字,只是在相应的文本中只有一个名字。例如,在这个数据中:pat < - c(“mary”,“john”,“anthony”) text < - c(“这是关于安东尼的长文本”,“这是另一个关于约翰的长文本” ,“这是关于玛丽的最终文本”)。我想在第一个文本中搜索“mary”,然后在第二个文本中搜索“john”,最后在第三个文件中搜索“anthony”。 – PhiSo

+0

请编辑您的问题并在那里添加解释。它让人们更容易帮助你。 – Abdou

回答

3

有了新的样本数据,哟可以这样做:

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 

希望这有助于。

+1

这很有帮助,谢谢。我在sapply(1:length(pat),function(x)grepl(pat [x],text [x],ignore.case = TRUE))中添加了参数“ignore.case = TRUE”),因为我需要查找大写和小写的名字。 – PhiSo

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") 

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]) 
} 
+0

不错的解决方案+1 – Florian

+0

谢谢!在mapply版本中,我如何添加“ignore.case = TRUE”参数?我需要它,因为在一些文本中,一些名字以大写字母出现,而另一些则以小写字母出现。 – PhiSo

+1

您可以使用MoreArgs参数添加参数:'mapply(grepl,pat,text,MoreArgs = list(ignore.case = TRUE))''。 – Florian

0

另一种方法是使用Vectorize

Vectorize(grepl)(pattern = pat, x = text, ignore.case = TRUE) 
# mary john anthony 
# FALSE TRUE FALSE