Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 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 Reply

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:/" 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...