我试图使用grepl检测术语,并且我得到了太多的误报。我希望可能有一种方法可以要求两个成功的匹配任何一个项目(我的数据段的手动编码,我试图使自动化至少大致对应于此,但我有大约5与手动编码一样多的积极因素。我没有看到grepl采取任何需要多个匹配的参数来触发TRUE。有没有办法要求两个匹配才能触发真正的发现?或者我应该使用其他功能吗?
GenericColumn <- cbind(grepl(Genericpattern, Statement$Statement.Text, ignore.case = TRUE))
编辑:
这是一个更具体的例子:
Examplepattern <- 'apple|orange'
ExampleColumn <- cbind(grepl(Examplepattern, Rexample$Statement.Text, ignore.case = TRUE))
现在,所有这些都将通过grepl触发。我只希望带有两个引用的项触发true。
示例数据:
Rexample <- structure(list(Statement.Text = structure(c(2L, 1L, 3L, 5L, 4L
), .Label = c("This apple is a test about an apple.", "This is a test about apples.",
"This orange is a test about apples.", "This orange is a test about oranges.",
"This orange is a test."), class = "factor")), .Names = "Statement.Text", row.names = c(NA,
5L), class = "data.frame")
所需输出:TRUE,FALSE,TRUE,TRUE,FALSE
答案 0 :(得分:1)
您可以尝试再次显式查找该模式的正则表达式,例如(?:apple|orange).*(?:apple|orange)
(pattern <- paste0("(?:", Examplepattern, ")", ".*", "(?:", Examplepattern, ")"))
#[1] "(?:apple|orange).*(?:apple|orange)"
grepl(pattern, Rexample$Statement.Text, ignore.case = TRUE, perl = TRUE)
#[1] FALSE TRUE TRUE FALSE TRUE
答案 1 :(得分:1)
您可以指定在正则表达式中使用大括号重复某些内容的次数,例如{2}
(正好是之前的两倍),{2,5}
(2-5次)或{{1 (2次或更多次)。但是,您需要在要匹配的单词之间允许使用单词,因此您需要使用{2,}
(0次或更多次)量化的通配符.
。
因此,如果您希望*
或apple
匹配两次(包括orange
和apple
,反之亦然),则可以使用
orange
如果您希望grepl('(apple.*|orange.*){2}', Rexample$Statement.Text, ignore.case = TRUE)
# [1] FALSE TRUE TRUE FALSE TRUE
重复两次或apple
重复两次(但不是orange
一次且apple
一次),请单独量化:
orange