0

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:

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)

0

2 Answers 2

2
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
Sign up to request clarification or add additional context in comments.

1 Comment

How did you know to call the arguments in the list x, y, and z and then the arguments in gsub ..1, ..2, and ..3? Is there a variation on pmap -- maybe pmap_dfr?? -- that would eliminate the need for "unlist"? I find purrr really confusing.
0

In base R:

df1$result <- Map(function(flag, str, replace, sub) {
  if(flag == 'No') return(str)
  else gsub(sub, replace, str, fixed = TRUE)
}, flag = df1$Flag, str = df1$Name, replace = df1$Substitution, sub = df1$Generic)

df1
#>            Name Generic Substitution Flag       result
#> 1 <HELLO>_World <HELLO>       hello1  Yes hello1_World
#> 2         World <HELLO>        world   No        World
#> 3 HELLO_<WORLD> <WORLD>       world1  Yes HELLO_world1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.