合并R中多个目录中的多个.txt文件 [英] Merge multiple .txt files from multiple directories in R
问题描述
合并来自不同子目录的.txt文件
Merge .txt files from different sub directories
我有一个文件夹,其中充满了过去日期的子文件夹(例如01_14),在每个日期文件夹中有11个名为01.txt,02.txt ...的文件...我如何将所有.txt文件合并到一个数据框中,其中一列的名称为该文件夹的来源,一列的名称为file
I have a folder that is filled with sub folders of past dates (01_14 for example), inside each date folder there are 11 files named 01.txt, 02.txt... How can I merge all the .txt files into one data frame, with one column with the name of the folder from where it came from and a column with the name of file from where it came from?
我的层次结构如下所示:
My hierarchy would look something like this:
\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
推荐答案
当我需要读取多个文件时,我使用读取。 stack 辅助函数,它基本上是read.table的包装器,但是它允许您还为每个文件添加额外的列。这是我可能会在您的方案中使用的方式。
When I need to read multiple files, i use a read.stack helper function which is basically a wrapper to read.table but it allows you to also add extra columns on a per-file basis. Here's how I might use it with your scenario.
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))
这篇关于合并R中多个目录中的多个.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!