unexpected - r windows path




Efficiently convert backslash to forward slash in R (6)

A solution without a snippet defintion is

writeClipboard(gsub("\\\\", "/", readClipboard()))

I am looking for an efficient way to convert back slash to forward slash in R. Sometime I copy the link of the directory from the 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".

Thanks.


Here is a one step method of converting the address from the clipboard

x  <- gsub  ( "\\\\",  "/",  readClipboard ()  ) 

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.


If I understand correctly, you do want to get rid of the string editing. In order to be able to use gsub you would have to change all the \ to \\ manually first. So, why not just change \ to / in first place?

If you have the string in the clipboard you can use

  x=scan("clipboard",what="string")

This gives

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

That is, it converts all \ to \\ automatically. I know - not very handy, but the only way I know to get around the editing.


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"

autohotkey program:

^+v::
StringReplace, clipboard, clipboard, \,/,All
send %clipboard%

after control+c the file path, use control + shift + v to paste





r