r - 在过滤器中使用 str_detect 和 & 的简写

标签 r stringr

我正在尝试使用 str_detect 的简写和&filter数据框:

library(tidyverse)
df <- data.frame(type = c("age", "age and sex", "sex"))
#          type
# 1         age
# 2 age and sex
# 3         sex

我想缩短这个管道

df %>% 
  filter(str_detect(type, "age") & str_detect(type, "sex"))
#          type
# 1 age and sex 

所以我想将过滤器通过管道连接到 map超过pattern <- c("age", "sex")也许可以使用 reduce不知何故?

谢谢

最佳答案

我们可以使用正则表达式来指定零个或多个字符(*),紧随“年龄”后接“性别”。 \\b 用于指定单词边界,这样就不会匹配“adage”等。

library(dplyr)
library(stringr)
df %>% 
   filter(str_detect(type, '\\bage\\b.*\\bsex'))

或者使用map/reduce

library(purrr)
df %>%
   filter(map(c('age', 'sex'), ~ str_detect(type, .x)) %>% reduce(`&`))

关于r - 在过滤器中使用 str_detect 和 & 的简写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61370919/

相关文章:

string - 将字符向量拆分为单个字符? (与粘贴或 stringr::str_c 相反)

r - 如何在 R 中使用 tidyr::separate 拆分字符串并保留分隔符字符串的值?

r - 提取具有特定条件的数据框行

R 文本挖掘 - 文本字段之间的交集

r - ggplot2 两组条形图和 y 变量的平均值

r - 在 gregexpr 和 str_extract_all 函数中进行量化的交替

r - paste/paste0 和 str_c 有什么区别?

r - 矢量化 stringr str_match 以删除 for 循环

r - 基于行成员的逻辑向量

r - R Markdown 和 Windows 中的多行 latex 方程