2

I often want to read in csv files and I get the path by using shift + right click and then clicking "copy path".

I paste this path into my code. See an example below:

read_csv("C:\Users\me\data\file.csv")

Obviously this doesn't work because of the backslashes. My current solution is to escape each one, so that my code looks like this:

read_csv("C:\\Users\\me\\data\\file.csv")

It works, but it's annoying and occasionally I'll get errors because I missed one of the backslashes.

I wanted to create a function automatically adds the extra slashes

fix_path <- function(string) str_replace(string, "\\\\", "\\\\\\\\")

but R won't recognize the string in the first place until the backslashes are taken care of.

Is there another way to deal with this? Python has the option of adding an "r" before strings to note that the backslashes should be treated just as regular backslashes, is there anything similar in R? To be clear, I know that I can escape the backslashes, but I am looking for a way to do it automatically.

Allen
  • 236
  • 3
  • 12
  • Does this help? https://www.rdocumentation.org/packages/base/versions/3.5.2/topics/file.path – makeyourownmaker Feb 27 '19 at 15:40
  • I'd avoid the backslash altogether. You can use a forward slash and it will work fine. If you're using Rstudio you can use ctrl + f and replace in a selection. I would opt to replace "\" with "/" – Chris Littler Feb 27 '19 at 15:44
  • Actually this: https://stackoverflow.com/questions/17605563/efficiently-convert-backslash-to-forward-slash-in-r – NelsonGon Feb 27 '19 at 16:04
  • @Allen From R 4.0.0 raw strings are supported. See [Escaping backslash () in string or paths in R](https://stackoverflow.com/questions/14185287/escaping-backslash-in-string-or-paths-in-r/63078969#63078969) – Henrik Aug 11 '20 at 16:14

1 Answers1

1

You can use this hack. Suppose you had copied your path as mentioned then you could use

scan("clipboard", "character", quiet = TRUE)

scan reads the text copied from the clipboard and takes care about the backslashes. Then copy again what is returned from scan

thothal
  • 16,690
  • 3
  • 36
  • 71