str_detect 使用 R 具有多个相同类型的字符串(而不是或)
str_detect with multiple strings (and not or) of the same kind using R
我想使用 str_detect 或类似方法来识别同一字符串至少分别出现两次的值。
例如,如果我想从 find.variable:
中两次识别其中包含“检测”一词的值
find.variable <- c("detect me a string detect", "detect string", "string", "detect detect", "detectdetect")
我想要的输出是:
logi [1:5] TRUE FALSE FALSE TRUE TRUE
值是否在字符串中重复并不重要,例如detectedetect,尽管有一个替代解决方案可能会很好,该解决方案排除字符串不是“检测”的结果,例如具有所需输出的结果:
logi [1:5] TRUE FALSE FALSE TRUE FALSE
这可能是以下内容的变体:
find.variable.string <- str_detect(find.variable, "detect")
但我也很高兴听到其他建议 - 我怀疑正则表达式可能是必要的。
您可以使用-
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
请注意,在 str_count
的情况下,最后一个值为 TRUE
。
我想使用 str_detect 或类似方法来识别同一字符串至少分别出现两次的值。
例如,如果我想从 find.variable:
中两次识别其中包含“检测”一词的值find.variable <- c("detect me a string detect", "detect string", "string", "detect detect", "detectdetect")
我想要的输出是:
logi [1:5] TRUE FALSE FALSE TRUE TRUE
值是否在字符串中重复并不重要,例如detectedetect,尽管有一个替代解决方案可能会很好,该解决方案排除字符串不是“检测”的结果,例如具有所需输出的结果:
logi [1:5] TRUE FALSE FALSE TRUE FALSE
这可能是以下内容的变体:
find.variable.string <- str_detect(find.variable, "detect")
但我也很高兴听到其他建议 - 我怀疑正则表达式可能是必要的。
您可以使用-
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
请注意,在 str_count
的情况下,最后一个值为 TRUE
。