How to replace backslash \ in R with gsub?

Viewed 1682

I would like to ammend some .tex files from within R. I read the file with readLines() but I cannot replace the following text.

tex <- "$\\times$"
new_tex <- gsub("$\\times$", "\\ $\\times$", tex)
new_tex

It seems that it cannot find the $\\times$ But even if it does, is it possible to write \ without escaping them?

Thank you in advance!

2 Answers

gsub uses regular expressions by default unless you set fixed=TRUE. In regular expressions $ means the end of the sentence , that's why it does not work.

This, instead should work :

new_tex <- gsub("$\\times$", "\\ $\\times$", tex,fixed=TRUE)

About the backslash, no, you can't write a backslash without escaping it. Otherwise, for example, it would be impossible for the R interpreter, to distinguish between a tab \t and a "backslash + t".

Without fixed = TRUE:

gsub("\\$\\\\times\\$", "\\\\ $\\\\times\\$", tex)
[1] "\\ $\\times$"

Unfortunately you need a lot of backslashes because you need to escape pretty much everything.

Related