Escaping \ in a string or path in R

Windows copies the path with \ , which R does not accept. So, I wanted to write a function that converts '\' to '/'. For instance:

 chartr0 <- function(foo) chartr('\','\\/',foo) 

Then use chartr0 as ...

 source(chartr0('E:\RStuff\test.r')) 

But chartr0 does not work. I guess I can’t escape '/'. I think escape / may be important in many other cases.

Also, is there a way in R, so I do not have to use chartr0 every time, but automatically convert the whole path, creating an environment in R that calls chartr0 or uses some kind of temporary use, for example, using options

+4
source share
3 answers

Your fundamental problem is that R will signal an error as soon as it sees one backslash before any character, except for a few lowercase letters, backslashes, quotation marks, or some conventions for entering octal, hexadecimal, or Unicode sequences. This is because the interpreter sees the backslash as a message to β€œescape” from the usual translation of characters and do something else. If you need one backslash in your character element, you need to enter 2 backslashes. This will create one backslash:

 nchar("\\") #[1] 1 

The section "character vectors" _Intro_to_R_ says:

"Character strings are entered using either matching double (") or single (') quotes, but are printed using double quotes (or sometimes without quotes). They use C-style escape sequences, using \ as the escape character, so \ is entered and printed as \, and inside the double quotes is entered as \ ". Other useful escape sequences are \ n, newline, \ t, tab and \ b, backspace-see? Quotes for a complete list.

  ?Quotes 
+6
source
 chartr0 <- function(foo) chartr('\\','/',foo) chartr0('E:\\RStuff\\test.r') 

You cannot write E: \ Rxxxx because R considers that R is escaped.

+1
source

The problem is that every slash and backslash in your code does not run correctly, resulting in an invalid string or an incorrect used string. You need to read which characters to avoid and how. Take a look at the list of escape sequences in the link below. Everything that is not specified there (for example, a slash) is processed literally and does not require any escaping.

http://cran.r-project.org/doc/manuals/R-lang.html#Literal-constants

0
source

All Articles