Split a file path into folder names vector

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

you can use the package DescTools to solve the problem:

library(DescTools)

SplitPath('C:/users/losses/development/R/loveResearch/src/signalPreprocess.R')

The output is:

$normpath
[1] "C:\\users\\losses\\development\\R\\loveResearch\\src\\signalPreprocess.R"

$drive
[1] "C:"

$dirname
[1] "/users/losses/development/R/loveResearch/src/"

$fullfilename
[1] "signalPreprocess.R"

$filename
[1] "signalPreprocess"

$extension
[1] "R"

Pretty convenient.


Try this (will work with both "/" and "\"):

split_path <- function(path) {
    rev(setdiff(strsplit(path,"/|\\\\")[[1]], ""))
} 

Results

split_path("/home/foo/stats/index.html")
# [1] "index.html" "stats"      "foo"        "home"

rev(split_path("/home/foo/stats/index.html"))
# [1] "home"       "foo"        "stats"      "index.html"

Edit

Making use of normalizePath, dirname and basename, this version will give different results:

split_path <- function(path, mustWork = FALSE, rev = FALSE) {
    output <- c(strsplit(dirname(normalizePath(path,mustWork = mustWork)),
                                             "/|\\\\")[[1]], basename(path))
    ifelse(rev, return(rev(output)), return(output))
}

split_path("/home/foo/stats/index.html", rev=TRUE)
# [1] "index.html" "stats"      "foo"        "home"       "D:" 

Tags:

R