我正在尝试使用 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/