Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ignore case with multiple strings using str_detect in R

I’m trying to use an "or" statement while ignoring case with str_detect. I want to convert everything that contains "ag" to "Agricultural" and everything that contains "field" to "Agricultural"

Here’s an example:

(dat <- 
  data.frame(Class = c("ag", "Agricultural--misc", "old field")))

This works:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(dat %>% 
  mutate(Class_2 = case_when(
    # Aggregate all Agricultural classes
    str_detect(Class, fixed("Ag", ignore_case=TRUE)) ~ "Agricultural",
    # Convert 'field' to Agricultural
    str_detect(Class, fixed("field", ignore_case=TRUE)) ~ "Agricultural",
    TRUE ~ Class)))

But I want to condense the two lines to just one line, as below:

(dat %>% 
    mutate(Class_2 = case_when(
      # Aggregate all Agricultural and field classes to Agricultural
      str_detect(Class, fixed("Ag|field", ignore_case=TRUE)) ~ "Agricultural",
      TRUE ~ Class)))

>Solution :

A possible solution would be to bring everything to lower case and match that with ag|field.

dat %>%
  mutate(Class_2 = case_when(
    str_detect(string = str_to_lower(Class),
               pattern = "ag|field") ~ "Agricultural",
    TRUE ~ Class
  ))

# A tibble: 3 × 2
  Class              Class_2     
  <chr>              <chr>       
1 ag                 Agricultural
2 Agricultural--misc Agricultural
3 old field          Agricultural
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading