【发布时间】:2015-12-20 01:27:52
【问题描述】:
我编写了一个获得所需结果的代码。我需要一些帮助来缩短我的代码。 代码的作用:
- 检索包含文件的所有目录(和子目录)的路径
- 将行分成两列 - 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()