rpathescaping

Efficiently convert forward slash to back slash in R


My question relates to the following question/answer from 2013: Efficiently convert backslash to forward slash in R

I posted a question to the solution proposed by 'Arun' and 'flodel' at the link above, but I am not certain it will pick up on anyone's radar particularly given the age of the proposed solution. So, I would like to ask my question as a new one.

The original problem centered around finding a way of converting a back slash to a forward slash which, for me, is a common step if I want to write an R-script and access data in a particular Windows path. Consequently, I use the proposed solution from 2013, gsub("\\", "/", x), a lot in my R-scripts. Many thanks for that!

Purely as an academic question, if I have a path with forward slashes, e.g.

pathR <- "C:/Users/jd/Documents/folder/file.txt"

Why doesn't the command:

gsub("/", "\\", pathR)

replace the forward slashes in pathR with back slashes so that I can recover the Windows path? All I get is the string with no slashes at all, i.e.: "C:UsersjdDocumentsfolderfile.txt"?

When I try the following, R prompts me with a '+' sign (see below):

> gsub("/", "\\", pathR)
[1] "C:UsersjdDocumentsfolderfile.txt"
> gsub("/", "\\\", pathR)
+

What is R expecting me to input that's missing?

Many thanks for your help.


Solution

  • You need to use 4 backslashes

    pathR <- "C:/Users/jd/Documents/folder/file.txt"
    result <- gsub("/", "\\\\", pathR)
    
    # Default print method shows special characters escaped
    result
    #> [1] "C:\\Users\\jd\\Documents\\folder\\file.txt"
    
    # Use cat() to show the result without escape characters
    cat(result)
    #> C:\Users\jd\Documents\folder\file.txt