Reputation: 151
Is there a fast and robust way to generate absolute paths from a mixture of absolute and relative paths in R
?
More concrete, I look for a function that can (robustly) interpret the ../
operator, and returns a "recursively" followed absolute path, as for example:
rel_path_1 <- "../../path1/path2/"
rel_path_2 <- "../final/"
abs_path <- "/home/username/foo/bar/glarb/zorb"
my_function(abs_path, rel_path_1)
# "/home/username/foo/bar/path1/path2/
my_function(abs_path, rel_path_2)
# "/home/username/foo/bar/glarb/final/
my_function(abs_path, rel_path_1, rel_path_2)
# "/home/username/foo/bar/glarb/path1/final/
I thought about fiddling around something with regex and counting path separators and ../
operators to truncate the ens, but I fear the result would be less then stable.
Upvotes: 0
Views: 455
Reputation: 342
What you are actually looking for is path normalization. The R package {fs} is doing this nicely. But you could also use base R. Here is your example with both solutions.
rel_path_1 <- "../../path1/path2/"
rel_path_2 <- "../final/"
abs_path <- "/home/username/foo/bar/glarb/zorb"
# using base R. mustWork = FALSE because the example uses non existent paths
normalizePath(file.path(abs_path, rel_path_1), mustWork = FALSE)
#> [1] "C:\\home\\username\\foo\\bar\\path1\\path2"
# using R package fs
fs::path_norm(fs::path(abs_path, rel_path_1))
#> /home/username/foo/bar/path1/path2
Created on 2022-01-05 by the reprex package (v2.0.1)
Upvotes: 2