合并R中多个目录中的多个.txt文件
合并不同子目录中的.txt文件 我有一个文件夹,里面有过去日期的子文件夹(例如01_14),每个日期文件夹中有11个文件,分别名为01.txt、02.txt。。。如何将所有的.txt文件合并到一个数据框中,其中一列包含它来自的文件夹名称,另一列包含它来自的文件名称 我的层次结构如下所示:合并R中多个目录中的多个.txt文件,r,merge,dataframe,rstudio,dir,R,Merge,Dataframe,Rstudio,Dir,合并不同子目录中的.txt文件 我有一个文件夹,里面有过去日期的子文件夹(例如01_14),每个日期文件夹中有11个文件,分别名为01.txt、02.txt。。。如何将所有的.txt文件合并到一个数据框中,其中一列包含它来自的文件夹名称,另一列包含它来自的文件名称 我的层次结构如下所示: \Data \01_14 01.txt 02.txt ... 11.txt \02_14
\Data
\01_14
01.txt
02.txt
...
11.txt
\02_14
01.txt
02.txt
...
11.txt
\03_14
01.txt
02.txt
...
11.txt
当我需要读取多个文件时,我使用一个helper函数,它基本上是read.table的包装器,但它允许您在每个文件的基础上添加额外的列。下面是我如何在您的场景中使用它
dir<-"Data"
subdir<-list.dirs(dir, recursive=F)
#get dir/file names
ff<-do.call(rbind, lapply(subdir, function(x) {
ff<-list.files(x, "\\.txt$", include.dirs = FALSE, full.names = TRUE)
data.frame(dir=basename(x), file=basename(ff),
fullpath=ff, stringsAsFactors=F)
}))
#read into data.frame
read.stack(ff$fullpath, extra=list(file=ff$file, dir=ff$dir))
dir试试这个:
fileNames <- list.files("Data", recursive = TRUE, full.names = TRUE)
fileContents <- lapply(fileNames, function(fileName)
paste(readLines(fileName, warn = FALSE), collapse = "\n"))
meta <- regmatches(fileNames, regexec(".*Data/(.*)/(.*)$", fileNames))
merged <- mapply(c, fileContents, lapply(meta, "[", -1), SIMPLIFY = FALSE)
as.data.frame(t(do.call(cbind, merged)))
文件名