我认为您可能想要与其他人发布的不同的东西。我可能是错的,但你使用的短语:
'A' occurs, then 'B', then 'C'
向我表明您想检查某些事情是否以特定顺序发生。
如果是这种情况,我建议您可以更明确地提出您的问题。您提供了一个 MWE 示例,但它可以在不需要stringi(我喜欢它作为一个包)的情况下变得更小,因为我怀疑您的推文看起来像"ACB"
现实中的任何东西。手工制作 3-5 个字符串可以在不加载另一个包的情况下完成此操作。还显示您想要的输出使问题更加明确,不需要解释。
df <- data_frame(var1=c(
"I think A is good But then C.",
"'A' occurs, then 'B', then 'C'",
"and a then lower with b that c will fail",
NA,
"what about A, B, C and another ABC",
"CBA?",
"last null"
))
var <- c('A', 'B', 'C')
library(stringi); library(dplyr)
df%>%
mutate(
count_abc = stringi::stri_count_regex(
var1,
paste(var, collapse = '.*?')
),
indicator = count_abc > 0
)
## var1 count_abc indicator
## 1 I think A is good But then C. 1 TRUE
## 2 'A' occurs, then 'B', then 'C' 1 TRUE
## 3 and a then lower with b that c will fail 0 FALSE
## 4 <NA> NA NA
## 5 what about A, B, C and another ABC 2 TRUE
## 6 CBA? 0 FALSE
## 7 last null 0 FALSE
## or if you only care about the summary compute it directly
df%>%
summarize(
count_abc = sum(stringi::stri_detect_regex(
var1,
paste(var, collapse = '.*?')
), na.rm = TRUE)
)
## count_abc
## 1 3
如果我错了,我为我的误解道歉。