循环读取和合并多个excel表在r [英] Loop for Read and Merge multiple excel sheets in r
问题描述
有很多关于XLConnect和XConnect阅读excel文件的帖子,如如何读取R编程中的多个excel表?,包括rbind函数,但没有人回答这个问题:
There are many posts about XLConnect and reading excel files in R with XLConnect like How to read multiple excel sheets in R programming?, including rbind function, but no one answers this question:
如果我有多个excel一个目录中的.xls文件我可以如何使用一个循环读取和合并
每一个?
If i had multiple excel .xls files in a directory how can i use a loop for reading and merging each one in order?
我有一个目录,所以我这样做: / p>
I have a directory so i do this:
setwd("C:/Users/usuario/Desktop")
library(rjava)
library(XLConnect)
该目录具有28个名为如下的excel文件:
That directory has 28 excel files named like this:
Bitacora_Metrocali_01_02_2014C
Bitacora_Metrocali_02_02_2014C
. ... ...
Bitacora_Metrocali_28_02_2014C
所以我需要使用函数合并它们:
合并(x,y,all = T)
So i need to merge them using the function: Merge(x,y,all=T)
所以可以在数据框中添加新的列。 thig是,我需要一个数据框,启动
合并第一个wht,然后按顺序添加所有新的工作表。感兴趣的所有excel
文件在表1中。
So it can add new columns to the dataframe. The thig is, i need a dataframe that starts merging the first wht the second,and then adding all the new sheets in order. All excel files of interest are in sheet 1.
THX!
推荐答案
这是否适合你:
# 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)
}
这篇关于循环读取和合并多个excel表在r的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!