# Replace "%" With "\%" In String

## 01 February 2022 - 1 answer

I need to make a character vector suitable for use in LaTeX, so I need to escape all the percent signs with a single backslash. So far, all I've been able to do is to get two backslash:

``````> text <- c("This is 60%", "This is 30%")
> gsub("%", "\\%", text, fixed=TRUE)
[1] "This is 60\\%" "This is 30\\%"
> gsub("%", "\\\\%", text, fixed=TRUE)
[1] "This is 60\\\\%" "This is 30\\\\%"
``````

As expected, if `fixed=FALSE` I get no backslash using `"\\%"` as a substitution or two backslash using `"\\%"' as a substitution. How can I get "This is 60\%" as a result?

In fact, the first version is already working:

``````text <- c("This is 60%", "This is 30%")
gsub("%", "\\%", text, fixed=TRUE)
[1] "This is 60\\%" "This is 30\\%"
``````

When you see `\\%` in the printed string, the first backslash is just an escape character for the second backslash, which is literal. Your output string is really this:

``````This is 60\%
``````