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

How can I rewrite in a more efficient way str_detect()?

mutate(method = cur_group_id(),
           method = paste0("M", method)) %>% 
    mutate(method = case_when(
      str_detect(variable, "testhc35") ~ "M2",
      str_detect(variable, "testhc36") ~ "M2",
      str_detect(variable, "testhc37") ~ "M2",
      str_detect(variable, "testhi1") ~ "M2",
      str_detect(variable, "testhi2") ~ "M2",
      str_detect(variable, "testhi3") ~ "M2",
      method == "M1" ~ "M1",
      str_detect(variable, "testhc38") ~ "M3",
      str_detect(variable, "testhc39") ~ "M3",
      str_detect(variable, "testhc40") ~ "M3",
      str_detect(variable, "testhi4") ~ "M3",
      str_detect(variable, "testhi5") ~ "M3",
      str_detect(variable, "testhi6") ~ "M3")) %>% 
    unite(method_trait, c("method", "trait"), sep = "")

I believe I can detect the first 6 rows with str_detect() altogether and then the final 6 rows as one row. But I am not sure how to do it.

>Solution :

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

You can be conciser with ranges:

...
str_detect(variable, "testhc3[5-7]")  ~ "M2",
str_detect(variable, "testhi[1-3]")   ~ "M2",
method == "M1"                        ~ "M1",
str_detect(variable, "testhc3[8-9]")  ~ "M3",
str_detect(variable, "testhc40")      ~ "M3"
str_detect(variable, "testhi[4-6]")   ~ "M3"
...

Then you could mix-in the or (|) operator:

...
str_detect(variable, "testh(c3[5-7]|i[1-3])")      ~ "M2",
method == "M1"                                     ~ "M1",
str_detect(variable, "testh(c3[8-9]|i[4-6]|c40)")  ~ "M3",
...
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