In R, with file.path
, you can convert a character vector into a full file path, automatically using the correct file separator for your platform :
> file.path("home", "foo", "script.R")
[1] "home/foo/script.R"
I'd like to do exactly the reverse : split a file path into a character vector of components. So far I almost manage to do it with a recursive function, but I don't find it very elegant :
split_path <- function(file) {
if(!(file %in% c("/", "."))) {
res <- c(basename(file), split_path(dirname(file)))
return(res)
}
else return(NULL)
}
Which gives :
> split_path("/home/foo/stats/index.html")
[1] "index.html" "stats" "foo" "home"
Do you know of any already existing function, or at least a better way to do such a thing ?
Thanks !
EDIT : I think I'll finally stick to this slightly different recursive version, thanks to @James, which should handle drive letters and network shares under Windows :
split_path <- function(path) {
if (dirname(path) %in% c(".", path)) return(basename(path))
return(c(basename(path), split_path(dirname(path))))
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…