gpt4 book ai didi

r - 将文件路径拆分为文件夹名称向量

转载 作者:行者123 更新时间:2023-12-04 05:23:41 24 4
gpt4 key购买 nike

在R中,使用file.path,可以使用适合您平台的正确文件分隔符自动将字符向量转换为完整文件路径:

> file.path("home", "foo", "script.R")
[1] "home/foo/script.R"

我想做相反的事情:将文件路径拆分为组件的字符向量。到目前为止,我几乎可以通过递归函数来做到这一点,但是我觉得它不是很优雅:
split_path <- function(file) {
if(!(file %in% c("/", "."))) {
res <- c(basename(file), split_path(dirname(file)))
return(res)
}
else return(NULL)
}

这使 :
> split_path("/home/foo/stats/index.html")
[1] "index.html" "stats" "foo" "home"

您是否知道任何现有功能,或者至少知道做这种事情的更好方法?

谢谢 !

编辑:我想,由于@James,我最终将坚持使用略有不同的递归版本,因为@James可以在Windows下处理驱动器号和网络共享:
split_path <- function(path) {
if (dirname(path) %in% c(".", path)) return(basename(path))
return(c(basename(path), split_path(dirname(path))))
}

最佳答案

您可以通过简单的递归函数来做到这一点,方法是终止dirname不变的时间:

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

关于r - 将文件路径拆分为文件夹名称向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29214932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com