【问题标题】:Split file path into file path and extension in R将文件路径拆分为R中的文件路径和扩展名
【发布时间】:2015-12-20 01:27:52
【问题描述】:

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

  1. 检索包含文件的所有目录(和子目录)的路径
  2. 将行分成两列 - a) 一列是路径,b) 另一列是带扩展名的文件名

我敢肯定会有更短的版本。期待帮助。

这是我的代码:

    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

【问题讨论】:

  • Splitting a file name 的可能重复项
  • 感谢您的快速回复。但我的问题不是“如何”分裂。我的问题是是否有人可以帮助我缩短我的代码。我可以使用此代码获得输出,但想学习 R 中的技巧。谢谢。
  • 链接的答案中有很多技巧。
  • 好的。感谢您的链接。祝你有美好的一天:)
  • basename(list.files(path, recursive=TRUE)) 怎么样,还要检查dirname()

标签: r string file


【解决方案1】:

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

library(gsubfn)
m <- strapply(a, '(.*)/(.*)', ~ c(FPath=x, FileName=y), simplify=rbind)
Final <- as.data.frame(m, stringsAsFactors = FALSE)

【讨论】:

  • 哇。谢谢。这绝对是诀窍!谢谢你教我这个。
猜你喜欢
  • 1970-01-01
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 2011-12-08
  • 2020-04-02
相关资源
最近更新 更多