Reputation: 415
I have this string.
temp <- "this is Mapof ttMapof qwqqwMApofRt it"
I have to get this as output.
"this is Mapof (Mapof) ttMapof (Mapof) qwqqwMapofRt it"
I am doing this: (Perfect no problem!)
temp <- gsub('Mapof\\b', 'Mapof (Mapof)', temp) #code line 1
"this is Mapof (Mapof) ttMapof (Mapof) qwqqwMapofRt it"
But the problem is I can not do this directly since i have to take 'pattern' and 'replacement' from a vector. So after extracting the 'pattern' and 'replacement' from that vector, I store them as following
inc_spelling <- "Mapof" #(pattern)
cor_spelling <- "Map of" #(replacement)
Now I am using paste() as following to to get the exact code line 1 (above), but it does not happen. See for yourself. What is wrong happening here?
txt <- paste0("temp <- gsub('",inc_spelling,"\\b','",inc_spelling," (",cor_spelling,")'"," ,temp)")
txt
"temp <- gsub('Mapof\\b','Mapof (Map of)' ,temp)"
eval(parse(text=txt))
temp
"this is Mapof ttMapof qewqeqwMapofdffd it"
It fails! Why is it happening? I am not able figure out the bug! If this task is not achievable from paste() please suggest another alternative. Thanks!
Upvotes: 2
Views: 1437
Reputation: 132736
If you want to use eval(parse())
(pro-tip: you dont. Tweak @MadScone's answer to fit your needs), you need more escapes (i.e., you need to escape the escape that escapes the original escape as well as the original escape. Do you see how crazy this gets? eval(parse())
should be avoided):
txt <- paste0("temp <- gsub('",inc_spelling,"\\\\b','",
inc_spelling," (",
cor_spelling,")'"," ,temp)")
print(eval(parse(text=txt)))
#[1] "this is Mapof (Map of) ttMapof (Map of) qwqqwMApofRt it"
Upvotes: 1
Reputation: 7526
The solution you have tried is more complicated that it needs to be. You can supply your vector arguments directly to gsub()
:
gsub(paste0(inc_spelling, '\\b'), cor_spelling, temp)
Or is this not what you're trying to do?
Upvotes: 5