After normalizing both file
and dir
, try to find a common
ancestor directory to build a path for file
relative to dir
.
Usage
relative_path(file, dir = getwd())
Arguments
- file
A single string with the path to a file or directory to transform as relative.
- dir
A single string with the "reference" directory (by default, the directory provided by
getwd()
.
Value
A single character string with the relative path, or file
unmodified if file
is totally unrelated to dir
.
Author
Philippe Grosjean phgrosjean@sciviews.org
Examples
relative_path("/Users/me/project/file.txt", "/Users/me/project")
#> [1] "file.txt"
relative_path("/Users/me/project/subdir/file.txt", "/Users/me/project")
#> [1] "subdir/file.txt"
relative_path("/Users/me/file.txt", "/Users/me/project")
#> [1] "../file.txt"
relative_path("/Users/me/subdir/file.txt", "/Users/me/project")
#> [1] "../subdir/file.txt"
relative_path("/Users/file.txt", "/Users/me/project")
#> [1] "../../file.txt"
relative_path("/Users/subdir1/subdir2/file.txt", "/Users/me/project")
#> [1] "../../subdir1/subdir2/file.txt"
relative_path("/Unrelated/file.txt", "/Users/me/project")
#> [1] "/Unrelated/file.txt"
# \donttest{
relative_path("file.txt", "/Users/me/project")
#> [1] "file.txt"
relative_path("~/file.txt", "/Users/me/project")
#> [1] "~/file.txt"
relative_path("./file.txt", "/Users/me/project")
#> [1] "./file.txt"
relative_path(file.path(getwd(), "data.io", "file.txt"))
#> [1] "data.io/file.txt"
# }