在R中的字符串或路径中转义反斜杠(\) [英] Escaping backslash (\) in string or paths in R

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

问题描述

Windows复制带有反斜杠 \ 的路径,R不接受。因此,我想编写一个函数,将 \ 转换为 / 。例如:

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

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

然后将 chartr0 用作...

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.

此外,是否有可能避免使用 chartr0 ,但可以通过在R中创建一个环境来自动转换所有路径,该环境调用 chartr0 或使用诸如选项

Also, is it possible to avoid the use chartr0 every time, but convert all path automatically by creating an environment in R which calls chartr0 or use some kind of temporary use like using options

推荐答案

来自 R 4.0.0 ,您可以使用 r''((...)" 将路径写为原始字符串常量,可避免需要转义:

From R 4.0.0 you can use r"(...)" to write a path as raw string constant, which avoids the need for escaping:

r"(E:\RStuff\test.r)"
# [1] "E:\\RStuff\\test.r"



有一种新语法可以指定原始字符常量,类似于C ++中使用的常量: r''(...)'' ... 不包含序列<$ c $的任何字符序列c>) 。这样,更容易编写包含反斜杠的字符串或单引号和双引号。有关更多详细信息,请参见?行情

There is a new syntax for specifying raw character constants similar to the one used in C++: r"(...)" with ... any character sequence not containing the sequence )". This makes it easier to write strings that contain backslashes or both single and double quotes. For more details see ?Quotes.

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

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