首页 > 解决方案 > str_detect 使用 R 具有多个相同类型的字符串(而不是或)

问题描述

我想使用 str_detect 或类似方法来分别识别相同字符串至少出现两次的值。

例如,如果我想从 find.variable 中两次识别带有单词“detect”的值:

find.variable <- c("detect me a string detect", "detect string", "string", "detect detect", "detectdetect")

我想要的输出是:

logi [1:5] TRUE FALSE FALSE TRUE TRUE

值是否在字符串中重复(例如检测检测)并不重要,尽管有一个替代解决方案可能会很好地排除字符串不是“检测”的结果,例如具有所需的输出:

logi [1:5] TRUE FALSE FALSE TRUE FALSE

这可能是以下变化:

find.variable.string <- str_detect(find.variable, "detect") 

但我也很高兴听到其他建议——我怀疑正则表达式可能是必要的。

标签: rregexstringgrepl

解决方案


你可以使用 -

library(stringr)

str_detect(find.variable, '\\bdetect\\b.*\\bdetect\\b')
#[1]  TRUE FALSE FALSE  TRUE FALSE

如果要允许 的连续值'detect',请使用

str_detect(find.variable, 'detect.*detect')

您还可以使用str_count来计算字符串中的检测次数。

str_count(find.variable, 'detect') == 2
#[1]  TRUE FALSE FALSE  TRUE  TRUE

请注意,最后一个值TRUEstr_count.


推荐阅读