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 "%" with "\%" in string

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?

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

>Solution :

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\%
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