user63230
user63230

Reputation: 4708

short hand for using str_detect and & in filter

I'm trying to get the short hand for using str_detect and & to filter a dataframe:

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

I want to shorten this pipe

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

So I'd like to pipe the filter to map over pattern <- c("age", "sex") and maybe use reduce somehow?

Thanks

Upvotes: 2

Views: 213

Answers (1)

akrun
akrun

Reputation: 887961

We can use a regex to specify zero or more characters (*) following the 'age' succeeded by 'sex'. The \\b is to specify word boundary so that it won't match 'adage' etc.

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

Or use map/reduce

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

Upvotes: 2

Related Questions