Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

r - Split a file path into folder names vector

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do it with a simple recursive function, by terminating when the dirname doesn't change:

split_path <- function(x) if (dirname(x)==x) x else c(basename(x),split_path(dirname(x)))
split_path("/home/foo/stats/index.html")
[1] "index.html" "stats"      "foo"        "home"       "/" 
split_path("C:\Windows\System32")
[1] "System32" "Windows"  "C:/"
split_path("~")
[1] "James"  "Users" "C:/" 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...