Split a file path into folder names vector

后端 未结 3 945
感情败类
感情败类 2020-12-18 00:17

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 :



        
相关标签:
3条回答
  • 2020-12-18 01:04

    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:" 
    
    0 讨论(0)
  • 2020-12-18 01:10

    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:/" 
    
    0 讨论(0)
  • 2020-12-18 01:13

    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.

    0 讨论(0)
提交回复
热议问题