是否有一种很好的内置方法可以将 R 中的相对文件路径转换为绝对路径,并且不需要文件系统上实际存在的路径?
base::normalizePath
和 tools::file_path_as_absolute
都在查找文件系统中的物理路径,因此当路径不存在时它们都会失败:
> normalizePath('foo')
[1] "foo"
Warning message:
In normalizePath("foo") : path[1]="foo": No such file or directory
> tools::file_path_as_absolute('foo')
Error in tools::file_path_as_absolute("foo") : file 'foo' does not exist
我可以编写以下函数,在类 Unix 系统上运行良好,但不能跨平台到 Windows 世界:
rel_to_abs <- function(x) {
# Convert `x` to absolute path - does not consult the file system
ifelse(grepl('^/', x), x, file.path(getwd(), x))
}
如果我遗漏了核心库中的某些内容,我很乐意被指出。
答案 0 :(得分:2)
您可以使用 getAbsolutePath
包中的 R.utils
:
> R.utils::getAbsolutePath("foo")
[1] "/home/stla/Work/R/foo"