2

I want to create a function to automatically correct single backslashes to double backslashes since R gives an error if you copy paste a path due to a single backslash. But when I try this, it gives an error:

> x<-gsub("\", "\\", "pak\istan")

Error: unexpected '\\' in "x<-gsub("\","\"

Then I tried this and got the same error again:

> x<-gsub("\", "\\", "pak\istan", fixed=TRUE)

Error: unexpected '\\' in "x<-gsub("\","\"

How can I fix it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

0

In the pattern argument of gsub you need to escape the backslash character, cf. gsub's documentation. That is, it needs to be a double backslash.

Furthermore, the backslash in "pak\istan" also needs to be escaped:

gsub("\\", "\\", "pak\\istan", fixed=TRUE)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
robertdj
  • 909
  • 1
  • 5
  • 10