| 1 |
#' Select path components by their position/index. |
| 2 |
#' |
| 3 |
#' `path_select_components()` allows to select individual components from |
| 4 |
#' an `fs_path` object via their index. |
| 5 |
#' |
| 6 |
#' `path_select_components()` is vectorized. |
| 7 |
#' |
| 8 |
#' @param path A path of class `fs_path`. |
| 9 |
#' @param index An integer vector of path positions. (A negative index will work |
| 10 |
#' according to R's usual subsetting rules.) |
| 11 |
#' @param from A character of either `"start"` or `"end"` to choose if indexing |
| 12 |
#' should start from the first or last component of the `path`. |
| 13 |
#' |
| 14 |
#' @return An `fs_path` object, which is a character vector that also has class |
| 15 |
#' `fs_path`. |
| 16 |
#' |
| 17 |
#' @export |
| 18 |
#' @examples |
| 19 |
#' path <- fs::path("some", "simple", "path", "to", "a", "file.txt") |
| 20 |
#' |
| 21 |
#' path_select_components(path, 1:3) |
| 22 |
#' |
| 23 |
#' path_select_components(path, 1:3, "end") |
| 24 |
#' |
| 25 |
#' path_select_components(path, -1, "end") |
| 26 |
#' |
| 27 |
#' path_select_components(path, 6) |
| 28 |
|
| 29 |
path_select_components <- function(path, index, from = c("start", "end")) { |
| 30 |
from <- match.arg(from) |
| 31 |
|
| 32 |
res <- fs_path(character(length(path))) |
| 33 |
ps <- fs::path_split(path) |
| 34 |
for (idx in seq_along(ps)) { |
| 35 |
path <- ps[[idx]] |
| 36 |
path_seq <- seq_along(path) |
| 37 |
|
| 38 |
if (length(index) > 0 && max(abs(index)) > length(path)) { |
| 39 |
stop("`seq` contains a higher number than the path has components.") |
| 40 |
} |
| 41 |
|
| 42 |
if (from == "start") { |
| 43 |
path <- path[index] |
| 44 |
} |
| 45 |
if (from == "end") { |
| 46 |
path_seq <- rev(rev(path_seq)[index]) |
| 47 |
path <- path[path_seq] |
| 48 |
} |
| 49 |
|
| 50 |
res[idx] <- fs::path_join(path) |
| 51 |
} |
| 52 |
|
| 53 |
res |
| 54 |
} |