djq
djq

Reputation: 15286

Raw text strings for file paths in R

Is it possible to use a prefix when specifying a filepath string in R to ignore escape characters?

For example if I want to read in the file example.csv when using windows, I need to manually change \ to / or \\. For example,

'E:\DATA\example.csv'

becomes

'E:/DATA/example.csv'

data <- read.csv('E:/DATA/example.csv')

In python I can prefix my string using r to avoid doing this (e.g. r'E:\DATA\example.csv'). Is there a similar command in R, or an approach that I can use to avoid having this problem. (I move between windows, mac and linux - this is just a problem on the windows OS obviously).

Upvotes: 42

Views: 42083

Answers (8)

G. Grothendieck
G. Grothendieck

Reputation: 269556

  1. If E:\DATA\example.csv is on the clipboard then do this:

     example.csv <- scan("clipboard", what = "")
     ## Read 1 item
     example.csv
     ## [1] "E:\\DATA\\example.csv"
    

Now you can copy "E:\\DATA\\example.csv" from the above output above onto the clipboard and then paste that into your source code if you need to hard code the path.

Similar remarks apply if E:\DATA\example.csv is in a file.

  1. If the file exists then another thing to try is:

    example.csv <- file.choose()

and then navigate to it and continue as in 1) above (except the file.choose line replaces the scan statement there).

  1. Note that its not true that you need to change the backslashes to forward slashes for read.csv on Windows but if for some reason you truly need to do that translation then if the file exists then this will translate backslashes to forward slashes (but if it does not exist then it will give an annoying warning so you might want to use one of the other approaches below):

    normalizePath(example.csv, winslash = "/")

and these translate backslashes to forward slashes even if the file does not exist:

gsub("\\", "/", example.csv, fixed = TRUE)
## [1] "E:/DATA/example.csv"

or

chartr("\\", "/", example.csv)
## [1] "E:/DATA/example.csv"
  1. In 4.0+ the following syntax is supported. ?Quotes discusses additional variations.

     r"{E:\DATA\example.csv}"
    

EDIT: Added more info on normalizePath. EDIT: Added (4).

Upvotes: 10

monte
monte

Reputation: 1865

I know this question is old, but for people stumbling upon this question in recent times, wanted to share that with the latest version R4.0.0, it is possible to parse in raw strings. The syntax for that is r"()". Note that the string goes in the brackets.

Example:

> r"(C:\Users)"
[1] "C:\\Users"

Source: https://cran.r-project.org/doc/manuals/r-devel/NEWS.html jump to section: significant user-visible changes.

Upvotes: 5

Michael Hoffman
Michael Hoffman

Reputation: 34324

No, this is not possible with R versions before 4.0.0. Sorry.

Upvotes: 4

Caleb Fitzgerald
Caleb Fitzgerald

Reputation: 426

It is now possible with R version 4.0.0. See ?Quotes for more.

Example

r"(c:\Program files\R)"
## "c:\\Program files\\R"

Upvotes: 31

Matthew Strasiotto
Matthew Strasiotto

Reputation: 369

To answer the actual question of "Can I parse raw-string in R without having to double-escape backslashes?" which is a good question, and has a lot of uses besides the specific use-case with the clipboard.

I have found a package that appears to provide this functionality:

https://github.com/trinker/pathr

See "win_fix". The use-case specified in the docs is exactly the use-case you just stated, however I haven't investigated whether it handles more flexible usage scenarios yet.

Upvotes: 1

Matt
Matt

Reputation: 994

Here's an incredibly ugly one-line hack to do this in base R, with no packages necessary:

setwd(gsub(", ", "", toString(paste0(read.table("clipboard", sep="\\", stringsAsFactors=F)[1,], sep="/"))))

Usable in its own little wrapper function thus (using suppressWarnings for peace of mind):

> getwd()
[1] "C:/Users/username1/Documents"
> change_wd=function(){
+   suppressWarnings(setwd(gsub(", ", "", toString(paste0(read.table("clipboard", sep="\\", stringsAsFactors=F)[1,], sep="/")))))
+   getwd()
+ }

Now you can run it:

#Copy your new folder path to clipboard
> change_wd()
[1] "C:/Users/username1/Documents/New Folder"

Upvotes: 2

Andrie
Andrie

Reputation: 179428

You can use file.path to construct the correct file path, independent of operating system.

file.path("E:", "DATA", "example.csv")
[1] "E:/DATA/example.csv"

It is also possible to convert a file path to the canonical form for your operating system, using normalizePath:

zz <- file.path("E:", "DATA", "example.csv")
normalizePath(zz)
[1] "E:\\DATA\\example.csv"

But in direct response to your question: I am not aware of a way to ignore the escape sequence using R. In other words, I do not believe it is possible to copy a file path from Windows and paste it directly into R.

However, if what you are really after is a way of copying and pasting from the Windows Clipboard and get a valid R string, try readClipboard

For example, if I copy a file path from Windows Explorer, then run the following code, I get a valid file path:

zz <- readClipboard()
zz
[1] "C:\\Users\\Andrie\\R\\win-library\\"

Upvotes: 44

Tyler Rinker
Tyler Rinker

Reputation: 109864

A slightly different approach I use with a custom made function that takes a windows path and corrects it for R.

pathPrep <- function() {                        
    cat("Please enter the path:\\n\\n")         
    oldstring <- readline()                     
    chartr("\\\\", "/", oldstring)              
}                                               

Let's try it out!

When prompted paste the path into console or use ctrl + r on everything at once

(x <- pathPrep())                      
C:/Users/Me/Desktop/SomeFolder/example.csv      

Now you can feed it to a function

shell.exec(x) #this piece would work only if    
              #  this file really exists in the 
              #  location specified  

But as others pointed out what you want is not truly possible.

Upvotes: 4

Related Questions