Home > Enterprise >  How to pass a chr variable into r"(...)"?
How to pass a chr variable into r"(...)"?

Time:03-11

I've seen that since 4.0.0, R supports raw strings using the syntax r"(...)". Thus, I could do:

r"(C:\THIS\IS\MY\PATH\TO\FILE.CSV)"
#> [1] "C:\\THIS\\IS\\MY\\PATH\\TO\\FILE.CSV"

While this is great, I can't figure out how to make this work with a variable, or better yet with a function. See this comment which I believe is asking the same question.

This one can't even be evaluated:

construct_path <- function(my_path) {
  r"my_path"
}

Error: malformed raw string literal at line 2
}
Error: unexpected '}' in "}"

Nor this attempt:

construct_path_2 <- function(my_path) {
  paste0(r, my_path)
}

construct_path_2("(C:\THIS\IS\MY\PATH\TO\FILE.CSV)")

Error: '\T' is an unrecognized escape in character string starting ""(C:\T"


Desired output

# pseudo-code
my_path <- "C:\THIS\IS\MY\PATH\TO\FILE.CSV"
construct_path(path)

#> [1] "C:\\THIS\\IS\\MY\\PATH\\TO\\FILE.CSV"

EDIT


In light of @KU99's comment, I want to add the context to the problem. I'm writing an R script to be run from command-line using WIndows's CMD and Rscript. I want to let the user who executes my R script to provide an argument where they want the script's output to be written to. And since Windows's CMD accepts paths in the format of C:\THIS\IS\MY\PATH\TO, then I want to be consistent with that format as the input to my R script. So ultimately I want to take that path input and convert it to a path format that is easy to work with inside R. I thought that the r"()" thing could be a proper solution.

CodePudding user response:

I think you're getting confused about what the string literal syntax does. It just says "don't try to escape any of the following characters". For external inputs like text input or files, none of this matters.

For example, if you run this code

path <- readline("> enter path: ")

You will get this prompt:

> enter path:

and if you type in your (unescaped) path:

> enter path: C:\Windows\Dir

You get no error, and your variable is stored appropriately:

path
#> [1] "C:\\Windows\\Dir"

This is not in any special format that R uses, it is plain text. The backslashes are printed in this way to avoid ambiguity but they are "really" just single backslashes, as you can see by doing

cat(path)
#> C:\Windows\Dir

The string literal syntax is only useful for shortening what you need to type. There would be no point in trying to get it to do anything else, and we need to remember that it is a feature of the R interpreter - it is not a function nor is there any way to get R to use the string literal syntax dynamically in the way you are attempting. Even if you could, it would be a long way for a shortcut.

  • Related