I want to output my R analysis with knitr, and I have a text which contains a row of underscores. I have to get them escaped, so to turn every _
into a \_
.
But because the backslash is also a special character in regex, I did not find a way to actually have a single backslash inserted before each underscore. It seems that odd numbers of backslashes produce an error (I guess the last one gets paired with the underscore) but trying to escape with even numbers didn't work either.
a <- "blah _ blah ___ blah"
> gsub("_", "\\_", a)
[1] "blah _ blah ___ blah"
> gsub("_", "\\\\_", a)
[1] "blah \\_ blah \\_\\_\\_ blah"
> gsub("_", "\\\_", a)
Error: '\_' is an unrecognized escape in character string starting ""\\\_"
> gsub("_", "\_", a)
Error: '\_' is an unrecognized escape in character string starting ""\_"
What is the correct way? It doesn't have to use gsub and regex, but I need the escapes easily applied to a single string.