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.

>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"))

Leave a Reply