简体   繁体   中英

substitute single backslash in R

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, eg 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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM