【问题标题】:How to manipulate file path in R?如何在R中操作文件路径?
【发布时间】:2014-03-31 07:59:12
【问题描述】:

我经常使用 windows 将文件路径复制并粘贴到 R 脚本中,结果如下:

file = 'C:\this\is\a\test.tif'

但是,这会导致错误,我必须手动将路径分隔符从 \ 切换到 /

>file = 'C:\this\is\a\test.tif'
Error: '\i' is an unrecognized escape in character string starting "'C:\this\i"

如果我使用的是 Python,我只需使用以下内容来正确格式化路径:

file = r'C:\this\is\a\test.tif'

是否有类似于 Python 的原始字符串 r'' 方法的 R 方法来快速格式化路径?

【问题讨论】:

标签: python r path formatting


【解决方案1】:

我能想到的最接近从 R 命令行工作时读取的原始字符串的方法是使用 scan 函数:

> tmp <- scan(what='')
1: 'C:\this\is\a\test.tif'
2: 
Read 1 item
> tmp
[1] "C:\\this\\is\\a\\test.tif"
> 

> tmp <- scan(what='',n=1)
1: C:\this\is\a\test.tif
Read 1 item
> tmp
[1] "C:\\this\\is\\a\\test.tif"
> cat(tmp, '\n')
c:\this\is\a\test.tif 

scan 函数将提示从控制台输入,您可以在那里键入或粘贴您想要的内容,在这种情况下,tmp 的打印表明反斜杠是按字面意思解释的(因此 print 显示它们是双倍的,并且 cat按原样显示)。

【讨论】:

  • 在console里是可以的,但是如何在代码编辑器中输入文件路径呢?
  • 如果在代码编辑器中工作,按原样粘贴,然后使用编辑器的查找和替换功能。或者使用控制台读取一次,然后使用dput 函数创建一个版本以粘贴到编辑器中。
猜你喜欢
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 2016-06-01
  • 2020-04-10
  • 2011-08-26
  • 2015-01-15
  • 1970-01-01
相关资源
最近更新 更多