首页 > 解决方案 > 将相对路径转换为绝对路径

问题描述

是否有一种很好的内置方法可以将相对文件路径转换为 ​​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))
}

如果我错过了核心库中的某些内容,我很乐意被指出。

标签: rpath

解决方案


您可以使用getAbsolutePathR.utils软件包:

> R.utils::getAbsolutePath("foo")
[1] "/home/stla/Work/R/foo"

推荐阅读