Efficiently convert backslash to forward slash in R

I use Path Copy Copy, which is a plug-in to Windows that allows you to create custom copy commands when you right-click a file/folder in Windows. So my right-click menu has "Copy Full Path with Forward Slash" as an option, which copies the file/folder with forward slashes. I am guessing it saves me days every year from manually changing slashes to R's format.


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.