循环读取和合并r中的多个excel表

有很多关于XLConnect的文章,以及如何使用XLConnect 读取 R中的excel文件?如何在R编程中读取多个Excel表格? 包括rbind函数,但没有人回答这个问题:

如果我有一个目录中有多个excel .xls文件,我怎样才能使用循环读取和合并每一个?

我有一个目录,所以我这样做:

setwd("C:/Users/usuario/Desktop") library(rjava) library(XLConnect) 

该目录有28个excel文件,命名如下:

  Bitacora_Metrocali_01_02_2014C Bitacora_Metrocali_02_02_2014C . ... ... Bitacora_Metrocali_28_02_2014C 

所以我需要使用函数合并它们:Merge(x,y,all = T)

所以它可以添加新的列到数据框。 thig是,我需要一个数据框,开始合并第一个,然后添加所有新的床单。 所有有兴趣的excel文件都在表1中。

谢谢!

这是否适合你:

 # This will give you a vector of the names of files in your current directory # (where I've assumed the directory contains only the files you want to read) data.files = list.files() # Read the first file df = readWorksheetFromFile(file=data.files[1], sheet=1) # Loop through the remaining files and merge them to the existing data frame for (file in data.files[-1]) { newFile = readWorksheetFromFile(file=file, sheet=1) df = merge(df, newFile, all=TRUE) } 

下面是一个lapplyReduce方法,我使用的是来自gdata包的read.xls,就像你提到的xls文件一样。 如果是xlsx ,则用read.xlsreplacereadWorksheetFromFile并加载相应的库。

 library(gdata) data.files = list.files(pattern = "*.xls") #get list of files data.to.merge <- lapply(files, read.xls) #read in files using lapply merged.data <- Reduce(function(...) merge(..., all = T),data.to.merge)#merge all the files 

merged.data将具有来自所有工作表的数据,并且还将处理具有不同标题的文件的情况。