在R中替换单反斜杠 [英] substitute single backslash in R

查看:634
本文介绍了在R中替换单反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在堆栈溢出中阅读了有关此主题的一些问题和答案,但仍然不知道如何解决这个问题:

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

我的目的是转换文件Windows资源管理器中的目录字符串可以在R中可识别的形式,例如C:\Users\Public需要转换为C:/ Users / Public,基本上单斜杠应该用正斜杠代替。但是,R不能存储原始字符串C:\Users\Public,因为\U和\P被视为转义符。

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"

我实际写的是一个GUI,最终的效果是,用户将目录输入或粘贴到输入字段中,按下一个按钮,然后程序将自动处理。

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?

推荐答案

当你需要使用反斜杠在R中的字符串中,您需要放置双反斜杠,此外,当您使用 gsub(\\,/,str)时,第一个参数被解析为正则表达式,它是无效的,因为它只包含一个必须转义的单个文字反斜杠。实际上,您需要使 gsub 将其视为纯文本 fixed = TRUE

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.

但是,您可能想使用 normalizePath ,请参阅这个SO线程

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

这篇关于在R中替换单反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆