在R中的字符串或路径中转义\ [英] Escaping \ in string or paths in R

查看:167
本文介绍了在R中的字符串或路径中转义\的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Windows以 \ 复制路径,R不接受。所以,我想写一个将'\'转换为'/'的函数。例如:

Windows copies path with \ which R does not accept. So, I wanted to write a function which would convert '\' to '/'. For example:

chartr0 <- function(foo) chartr('\','\\/',foo)

然后使用 chartr0 as ..

Then use chartr0 as...

source(chartr0('E:\RStuff\test.r'))

但是 chartr0 不工作。我猜,我无法逃脱'/'。我想逃脱 / 可能在许多其他场合很重要。

But chartr0 is not working. I guess, I am unable to escape '/'. I guess escaping / may be important in many other occasions.

另外,R中有没有一种方法,所以我不必每次都使用 chartr0 路径自动通过在R中创建一个环境调用 chartr0 或使用某种临时使用,如使用选项

Also, is there a way in R such that I do not have to use chartr0every time but convert all path automatically by creating an environemnt in R which calls chartr0 or use some kind of temporary use like using options

推荐答案

您的根本问题是,只要在除几个字符之外的任何字符之前看到单个反斜杠,R将发出错误条件小写字母,反斜杠本身,引号或一些用于输入八进制,十六进制或Unicode序列的约定。那是因为解释者将反斜杠视为消息,以逃避字符的通常翻译,并做其他事情。如果您希望在字符元素中使用单个斜杠,则需要键入2个反斜杠。这将创建一个反斜杠:

Your fundamental problem is that R will signal an error condition as soon as it sees a single back-slash before any character other than a few lower-case letters, backslashes themselves, quotes or some conventions for entering octal, hex or Unicode sequences. That is because the interpreter sees the back-slash as a message to "escape" the usual translation of characters and do something else. If you want a single back-slash in your character element you need to type 2 backslashes. That will create one backslash:

nchar("\\")
#[1] 1

_Intro_to_R_的字符向量部分说:

The "Character vectors" section of _Intro_to_R_ says:

使用匹配的双()或单(')引号输入字符串,但使用双引号(或有时不带引号)打印。它们使用C风格的转义序列,使用\作为转义字符,因此\输入并打印为\,并将双引号内的输入为\。其他有用的转义序列是\\\
,newline,\t,tab和\b,backspace-see?完整列表的引号。

"Character strings are entered using either matching double (") or single (') quotes, but are printed using double quotes (or sometimes without quotes). They use C-style escape sequences, using \ as the escape character, so \ is entered and printed as \, and inside double quotes " is entered as \". Other useful escape sequences are \n, newline, \t, tab and \b, backspace—see ?Quotes for a full list."

 ?Quotes

这篇关于在R中的字符串或路径中转义\的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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