Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a good built-in way to convert relative file paths to absolute paths in R, that doesn't require the path to actually exist on the filesystem?

Both base::normalizePath nor tools::file_path_as_absolute are looking up physical paths in the filesystem, so they both fail when the path doesn't exist:

> 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

I can write the following function that does a decent job on Unix-like systems, but isn't cross-platform to a Windows world:

rel_to_abs <- function(x) {
  # Convert `x` to absolute path - does not consult the file system
  ifelse(grepl('^/', x), x, file.path(getwd(), x))
}

If I've missed something in the core libraries, I'd be happy to be pointed to it.

question from:https://stackoverflow.com/questions/65621434/convert-relative-to-absolute-path

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
258 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use getAbsolutePath of the R.utils package:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...