r - 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")
但我也很高兴听到其他建议——我怀疑正则表达式可能是必要的。
解决方案
你可以使用 -
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
请注意,最后一个值TRUE
是str_count
.
推荐阅读
- python - 无法使用 Beautifulsoup 正确抓取标签
- python - 查找、替换和保存 xlsx 文件的脚本
- python - Pandas 根据当前行值从另一个数据框中获取最后 N 条记录的列值作为列表
- macos - Mac Catalyst 的 UIDocumentPickerViewController 配置
- geopandas - 从osmnx python中的多个位置选择建筑物
- c# - 使用数组数据生成多个立方体
- wordpress - 无法使用 Adspro Wordpress 插件管理 Google AdSense
- graph - 如何使用 apache tinkerpop gremlin 重新创建顶点?
- angular - 显示 Eslint 时间执行
- java - Java Lucene 如何找到类 TermFreqVector 和类 TermPositionVector?