Efficiently convert backslash to forward slash in R

I am looking for an efficient way to convert back slash to forward slash in R. Sometime I copy the link of the directory in Windows and I get something like this:

C:\Users\jd\Documents\folder\file.txt

How can I quickly change this to C:/Users/jd/Documents/folder/file.txt ? I cannot even read the above expression as character. It throws an error

"\u used without hex digits in character string starting ""C:\u".

I know TAB function in R helps to find the location fast, but was just wondering if there was any other work around. I could change the working directory to the location of folder also. I was just playing around and tried to convert backslash to forward slash and was not straight forward so asked this just because of curiosity.


In R, you've to escape the \ with \\ So, your path should be:

x <- "C:\\Users\\jd\\Documents\\folder\\file.txt"

To get that, you can do:

x <- readline()

then, at the prompt, paste your unmodified path (CTRL+V then ENTER)

Finally, to change \\ to / everywhere, you could use gsub, once again by escaping the \, but twice, as follows:

gsub("\\\\", "/", x)
# [1] "C:/Users/jd/Documents/folder/file.txt"

If you want the least number of keystrokes to convert backslashes when pasting paths, use an RStudio snippet defined as follows:

snippet pp
    "`r gsub('"', "", gsub("\\\\", "/", readClipboard()))`"

Remember to preface the second line with a tab, not multiple spaces for the snippet to work.

Then type pp, TAB, ENTER and the text on your clipboard is pasted, backslashes replaced with forward slashes and surrounded by quotes.

Here is the steps I usually take to copy file paths to RStudio once the above snippet has been defined:

  1. Navigate to file path in explorer.
  2. If copying a file path then: Shift + Right click on file, then click Copy as path.
  3. If copying a folder path then: Alt + d, Ctrl + c.
  4. Change window to RStudio and focus in R script where you want to paste the path.
  5. pp, TAB, ENTER to paste into RStudio and convert backslashes to forward slashes.