R - gsub replacing backslashes

Solution 1:

Here's what you need:

gsub("\\\\", "\\\\\\\\", "\\")
[1] "\\\\"

The reason that you need four backslashes to represent one literal backslash is that "\" is an escape character in both R strings and for the regex engine to which you're ultimately passing your patterns. If you were talking directly to the regex engine, you'd use "\\" to indicate a literal backslash. But in order to get R to pass "\\" on to the regex engine, you need to type "\\\\".


(If you are just wanting to double backslashes, you might want to use this instead):

gsub("\\", "\\\\", "\\", fixed=TRUE)
[1] "\\\\"