在过滤器中使用str_detect和&的短手。

问题描述 投票:1回答:1

我想得到使用的短手。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 某种程度上?

谅谅

r stringr
1个回答
2
投票

我们可以使用regex来指定0个或多个字符(*)后面的 "年龄 "和 "性别"。在 "性别 "之后的 \\b 是为了指定词的边界,这样就不会与'谚语'等相匹配。

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(`&`))
© www.soinside.com 2019 - 2024. All rights reserved.