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

Populate a column based on a pattern in another column

I have a DF where I am trying to populate a column based on whether a pattern in a string exists.

A      B     
E3Y12
E3Y45
E3Y56
c1234
c56534
c3456

I would like to check if A contains the string ‘E3Y’ and populate the column B with "This one" or if it doesn’t contain that pattern "That one"

I’ve tried the dplyr starts_with inside a case_when() and ifelse() statement with no avail since it has to be part of a select function.

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

>Solution :

You can use str_detect() to evaluate if a string contains a certain pattern and then using an ifelse is straightforward:

library(dplyr)
tibble( A = c(
"E3Y12",
"E3Y45",
"E3Y56",
"c1234",
"c56534",
"c3456")) %>% 
  mutate(B = ifelse(stringr::str_detect(A, "E3Y"), "This one", "That one"))
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