fs
fs copied to clipboard
selecting path elements by position
I just needed to select some path elements by position and thought this should be provided by fs.
Sth. like (maybe also vectorized over path):
library(fs)
path_select <- function(path, seq, from = c("start", "end")) {
from <- match.arg(from)
if (length(path) > 1) {stop("Please supply only one path.")}
path <- unlist(fs::path_split(path))
path_seq <- seq_along(path)
if (max(seq) > length(path)) {stop("`seq` contains a higher number than the path has elements.")}
if (from == "start") {path <- path[seq]}
if (from == "end") {
path_seq <- rev(rev(path_seq)[seq])
path <- path[path_seq]
}
path <- fs::path_join(path)
return(path)
}
path <- path("some", "simple", "path", "to", "a", "file.txt")
path_select(path, 1:3)
#> some/simple/path
path_select(path, 1:3, "end")
#> to/a/file.txt
path_select(path, -1, "end")
#> some/simple/path/to/a
path_select(path, 3:4)
#> path/to
Created on 2021-04-19 by the reprex package (v0.3.0)
Are you interested in submitting a PR?