将多个文本文件导入R

时间:2012-05-21 08:37:40

标签: r import

我有四个包含相同名称的文本文件(制表符分隔)的文件夹,我想将所有这些文本文件导入到data.frame中。例如:

TopFolder = "G:\\University" 
SubFolder = list.files(TopFolder)
#find the name of the folders in the current directory
DateTime = rbind(read.table(paste(TopFolder,SubFolder[1],"Data.txt",sep = "\\"),sep="\t"),
                read.table(paste(TopFolder,SubFolder[2],"Data.txt",sep = "\\"),sep="\t"),
                 read.table(paste(TopFolder,SubFolder[3],"Data.txt",sep = "\\"),sep="\t"),
                 read.table(paste(TopFolder,SubFolder[4],"Data.txt",sep = "\\"),sep="\t"))

这个例子工作正常,虽然我希望使用循环或其他函数来生成这个变量,而不必单独导入所有文件。有没有人有什么建议?

1 个答案:

答案 0 :(得分:4)

这个怎么样?

lf = list.files(path = "G:\\University", pattern = "Data.txt", 
                full.names = TRUE, recursive = TRUE, include.dirs = TRUE)

library(plyr)
DateTime = ldply(lf, read.table, sep = "\t")