substitute single backslash in R

2019-06-21 18:39发布

问题:

I have read some questions and answers on this topic in stack overflow but still don't know how to solve this problem:

My purpose is to transform the file directory strings in windows explorer to the form which is recognizable in R, e.g. C:\Users\Public needs to be transformed to C:/Users/Public, basically the single back slash should be substituted with the forward slash. However the R couldn't store the original string "C:\Users\Public" because the \U and \P are deemed to be escape character.

dirTransformer <- function(str){
   str.trns <- gsub("\\", "/", str)
   return(str.trns)
   }

str <- "C:\Users\Public"
dirTransformer(str)

> Error: '\U' used without hex digits in character string starting ""C:\U"

What I am actually writing is a GUI, where the end effect is, the user types or pastes the directory into a entry field, pushes a button and then the program will process it automatically.

Would someone please suggest to me how to solve this problem?

回答1:

When you need to use a backslash in the string in R, you need to put double backslash. Also, when you use gsub("\\", "/", str), the first argument is parsed as a regex, and it is not valid as it only contains a single literal backslash that must escape something. In fact, you need to make gsub treat it as a plain text with fixed=TRUE.

However, you might want to use normalizePath, see this SO thread.



回答2:

dirTransformer <- function(str){
  str.trns <- gsub("\\\\", "/", str)
  return(str.trns)
}

str <- readline()
C:\Users\Public

dirTransformer(str)

I'm not sure how you intend the user to input the path into the GUI, but when using readline() and then typing C:\Users\Public unquoted, R reads that in as:

> str
[1] "C:\\Users\\Public"

We then want to replace "\\" with "/", but to escape the "\\" we need "\\\\" in the gsub.

I can't be sure how the input from the user is going to be read into R in your GUI, but R will most likely escape the \s in the string like it does when using the readline example. the string you're trying to create "C:\Users\Public" wouldn't normally happen.