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

Replace String in one column from another string in different column based on a flag

Let’s assume I have a dataset like this one:

df1 = data.frame(Name=c("<HELLO>_World","World","HELLO_<WORLD>"),
                 Generic=c("<HELLO>","<HELLO>","<WORLD>"),
                 Substitution = c("hello1","world","world1"),
                 Flag = c("Yes","No","Yes"))

Now, based on the flag, I’d like to obtain the replacement in the "Name" column of the string in the substitution one, In the end the dataframe should look like this:

final <- data.frame(Name=c("hello1_World","world","HELLO_world1"))

I’ve tried with something like this:

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

index <- df1$Flag == "Yes"
df1$Name[index] <- gsub(df1$Generic[index],df1$Substitution[index])

Maybe it should be done in a new column (also acceptable)

>Solution :

library(tidyverse)
df1 %>%
  mutate(new_name = ifelse( 
    Flag == "Yes",
    unlist(purrr::pmap(list(x = Generic, y = Substitution, z = Name), 
                       ~ gsub(..1, ..2, ..3))),
    Name))

#             Name Generic Substitution Flag     new_name
# 1: <HELLO>_World <HELLO>       hello1  Yes hello1_World
# 2:         World <HELLO>        world   No        World
# 3: HELLO_<WORLD> <WORLD>       world1  Yes HELLO_world1
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