Returns the nth ancestor directory of a given path.
Arguments
- path
Character. The file or directory path to start from. If
check_dir = TRUE
andpath
exists as a file or has a file extension, its parent directory is used as the starting point. Ifcheck_dir = FALSE
, a file path is treated as a directory name.- levels
Integer. Number of parent levels to jump up. Must be a single, non-negative integer.
- check_dir
Logical. If
TRUE
, checkspath
is a valid directory and uses its parent ifpath
is a file. IfFALSE
, does not check existence and uses the input as-is.- extract_full
Logical. If
TRUE
andlevels
exceeds the number of path components minus one, returns the root of the path. IfFALSE
, an error is thrown whenlevels
exceeds the available ancestors.- ...
Additional arguments passed to stop_ctx for error reporting.
Value
Character. The resulting path after jumping. If extract_full = TRUE
and levels
exceeds the available ancestors, returns the root of the path;
otherwise, returns the ancestor path or throws an error.
Examples
parent_dir("/home/user/projects/data/file.txt", levels = 2)
#> /home/user/projects
# this will give an error
try(parent_dir("/home/user", levels = 4, extract_full = TRUE))
#> Error in parent_dir("/home/user", levels = 4, extract_full = TRUE) :
#> `levels` > available ancestors (max = 2). - 19:40:36
#>
#> ----- Metadata -----
#>
#> levels [levels]: <integer>
#> 4
#>
#> abs_depth [abs_depth]: <integer>
#> 3
#>
#> extract_full [extract_full]: <logical>
#> TRUE