将文件路径拆分为R

时间:2015-09-22 21:50:35

标签: r string file

我编写了一个获得所需结果的代码。我想要一些帮助来缩短我的代码。 代码的作用:

  1. 检索包含文件的所有目录(和子目录)的路径
  2. 将这些行拆分为两列 - a)一列是路径,b)另一列是带扩展名的文件名
  3. 我确信可以有更短的版本。期待着帮助。

    这是我的代码:

        library(stringr)
        setwd("/Users/Guest/Desktop/Project") #set Working Directory
        path <-"/Users/Guest/Desktop/Project"  #set path to retrieve files
        a <- list.files(path,recursive = TRUE) #retrieve files in variable a
        last <- str_locate(a,"(.*)/") #locate the last "/"
        sub <- str_sub(a,last[,2:2] + 1) #split from the last "/"
        adf <- as.data.frame(a,stringsAsFactors= FALSE) #convert to DF
        colnames(adf) <- "FPath" #ColumnName
        subdf <- as.data.frame(sub, stringsAsFactors = FALSE) #Convert to DF
        colnames(subdf) <- "FileName" #ColumnName
        Final <- cbind(adf,subdf) #Join both DF's
        Final <- within(Final, FileName <- ifelse(is.na(FileName), FPath, FileName)) #If there are files directly in root folder (Project), then FileName is NULL so replace it with FPath.
        Final
        write.table(Final, file = "Final_Import2.txt", quote = FALSE, row.names = FALSE, sep ="\t") #WritetoFile
    

1 个答案:

答案 0 :(得分:1)

除了链接中提供的答案之外,这是一种可能有帮助的方法:

['Mon Sep 1 16:40:20 2015', 'Mon Sep 1 16:45:20 2015',
 'Mon Sep 1 16:50:20 2015', 'Mon Sep 1 16:55:20 2015']