replacing single backslash with double backslash in r

Viewed 37

I want to create a function to automatically correct single backslash to double backslash since r gives an error if you copy paste path due to 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 same error again

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

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

please help

1 Answers

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

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

gsub("\\","\\","pak\\istan", fixed=TRUE)
Related