我正在尝试使用文本搜索模式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").
Run Code Online (Sandbox Code Playgroud)
我想"mary"在第一个文本中搜索,然后"john"在第二个文本中搜索,最后"anthony"在第三个文本中搜索.
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")
Run Code Online (Sandbox Code Playgroud)
的Map或mapply功能会做到这一点:
Map(grepl,pat,text)
Run Code Online (Sandbox Code Playgroud)
(这会返回一个列表,你可以unlist)
要么
mapply(grepl,pat,text)
Run Code Online (Sandbox Code Playgroud)
(自动简化)或
n <- length(pat)
res <- logical(n)
for (i in seq(n)) {
res[i] <- grepl(pat[i],text[i])
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用Vectorize
Vectorize(grepl)(pattern = pat, x = text, ignore.case = TRUE)
# mary john anthony
# FALSE TRUE FALSE
Run Code Online (Sandbox Code Playgroud)
使用新的示例数据,您可以执行以下操作:
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]))
Run Code Online (Sandbox Code Playgroud)
返回:
[1] FALSE TRUE FALSE
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
1074 次 |
| 最近记录: |