Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw text strings for file paths in R

Tags:

string

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).

like image 923
djq Avatar asked Nov 19 '11 20:11

djq


People also ask

What is the prefix R stands for in file path?

The r prefix on strings stands for “raw strings”. Standard strings use backslash for escape characters: “\n” is a newline, not backslash-n.

What is a relative path r?

setwd(path) changes the current working directory. list. files(path) prints a list of files and directories of a specific directory; or list. files() on its own for the current working directory. A relative path specifies a location starting from the current location.


1 Answers

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\\" 
like image 120
Andrie Avatar answered Sep 20 '22 08:09

Andrie