我希望获得R中文件的完全限定名称,给出任何标准符号.例如:
path.expand)通过完全限定的文件名,我的意思是,例如,(在类Unix系统上):
/home/user/some/path/file.ext
(已编辑 - 使用file.path并尝试Windows支持)粗略的实现可能是:
path.qualify <- function(path) {
path <- path.expand(path)
if(!grepl("^/|([A-Z|a-z]:)", path)) path <- file.path(getwd(),path)
path
}
Run Code Online (Sandbox Code Playgroud)
但是,我理想地喜欢可以处理相对路径的跨平台../,符号链接等.一个只有R的解决方案将是首选(而不是shell脚本或类似),但我找不到任何直接的方法来做到这一点,而不是"从头开始"编码.
有任何想法吗?
Rei*_*son 10
我想你想要normalizePath():
> setwd("~/tmp/bar")
> normalizePath("../tmp.R")
[1] "/home/gavin/tmp/tmp.R"
> normalizePath("~/tmp/tmp.R")
[1] "/home/gavin/tmp/tmp.R"
> normalizePath("./foo.R")
[1] "/home/gavin/tmp/bar/foo.R"
Run Code Online (Sandbox Code Playgroud)
对于Windows,winslash您可能希望一直设置参数,因为除了Windows之外的其他任何操作都会忽略它,因此不会影响其他操作系统:
> normalizePath("./foo.R", winslash="\\")
[1] "/home/gavin/tmp/bar/foo.R"
Run Code Online (Sandbox Code Playgroud)
(你需要逃避\因此\\)或
> normalizePath("./foo.R", winslash="/")
[1] "/home/gavin/tmp/bar/foo.R"
Run Code Online (Sandbox Code Playgroud)
取决于您希望路径的显示/使用方式.前者是默认值("\\"),所以你可以坚持使用它,如果它足够,而不需要明确地设置任何东西.
在R 2.13.0上,该"~/file.ext"位也有效(见注释):
> normalizePath("~/foo.R")
[1] "/home/gavin/foo.R"
Run Code Online (Sandbox Code Playgroud)