substitute single backslash in R

烈酒焚心 提交于 2019-12-12 10:42:57

问题


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.



来源:https://stackoverflow.com/questions/39164239/substitute-single-backslash-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!