Paste windows path converting backslashes to slashes automatically


#1

Hi,

I use RStudio 1.1.419 on Windows 7.
When I need to copy a file or directory path into my script, from an Explorer window for example, i then need to manually replace \ by / in order to get a valid path.
Is there a kind of "paste path replacing \" option in Rstudio ?

thanks for your help !


#2

For your specific issue, one R based solution I'm aware of is to use the utils function readClipboard()

For example, if you copy "C:\Program Files\R" from the address bar of windows explorer

image

Then in the console do:

fp <- readClipboard()
fp
#> [1] "C:\\Program Files\\R"

You'll see
"C:\Program Files\R" has automagically been converted to
"C:\\Program Files\\R" (which also works in the same way as using a forward slash / does)

In more general terms there's also the base function file.path() and also the here package if you'd like to construct file paths in a more platform independent way...

Hope this helps...


#3

markdly's suggestion is pretty neat. I don't use windows much but have seen this windows-explorer file path box and can see how you'd rely on it.

Auto Complete File Path - Another suggestion, I quite like just using RStudio IDE's autocomplete when you're filing out a filepath string. If you're unfamiliar with this, if you start with a function that requires a filepath, e.g. read.csv(file = "") and put your cursor between the two quote-marks, and then hit tab, RStudio will help guide you to a file path. You can start typing C: to start that path from your C-drive.


#4

thanks markdly,
i think the best solution for me is to have an add-in which executes the following code : normalizepath(readClipboard(),winslash = "/")
With a keyboard shortcut for it, it will be perfect :slight_smile: