View source: R/get_path_info.R
| get_path_info | R Documentation |
get_path_info is a merged, upgraded replacement for get_path_segment and
get_filename. It operates in two modes:
Mode A (when n is specified): Extract a specific path segment by
position, supporting forward indexing, reverse indexing, and range extraction.
Mode B (when n = NULL): Extract the filename, with optional removal
of the file extension and/or the directory prefix.
get_path_info(path, n = NULL, rm_extension = TRUE, rm_path = TRUE)
path |
A |
n |
A
|
rm_extension |
A
|
rm_path |
A |
Path normalisation (internal, fully vectorised):
All backslashes and consecutive slashes are collapsed to a single /.
Windows drive letter prefixes (C:, D:, etc.) are stripped for
segment indexing (and restored in full-path mode).
Leading and trailing / characters are removed.
Paths that are empty after the above steps (e.g. original inputs "C:/",
"/", "") are coerced to NA_character_.
Extension-stripping behaviour (internal .strip_ext helper):
| Input | Output | Notes |
"report.txt" | "report" | Standard file — last extension removed |
"data.tar.gz" | "data.tar" | Compound extension — only last level removed |
".bashrc" | ".bashrc" | Pure dot-file (no second dot) — unchanged |
".report.xlsx" | ".report" | Dot-file with extension — extension removed |
"no_ext" | "no_ext" | No extension — returned as-is |
"file." | "file." | Trailing isolated dot — returned as-is |
NA safety:
strsplit(NA_character_, ...) returns list(NA) with length 1, not
character(0). Consequently, every vapply callback guards against NA paths
with an explicit anyNA(x) check rather than length(x) == 0.
A character vector of the same length as path:
Returns the extracted segment string when the segment exists.
Returns NA_character_ when the segment index exceeds the path depth,
the input element is NA, or the path reduces to empty after normalisation
(e.g. "C:/", "/").
base::basename(), tools::file_path_sans_ext()
paths <- c("C:/Users/foo/Documents/report.xlsx",
"/home/user/.bashrc",
"relative/path/to/data.csv",
".hidden.tar.gz",
NA_character_)
# Mode B: filename only, extension stripped (default)
get_path_info(paths)
# Mode B: filename only, extension preserved
get_path_info(paths, rm_extension = FALSE)
# Mode B: full normalised path, extension stripped
get_path_info(paths, rm_path = FALSE)
# Mode A: extract the 2nd path segment
get_path_info(paths, n = 2)
# Mode A: extract the last segment with extension stripped (n = -1 linkage)
get_path_info(paths, n = -1, rm_extension = TRUE)
# Mode A: range extraction
get_path_info(paths, n = c(2, 3))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.