在R中导入多个具有文件名的Excel文件 [英] Importing multiple Excel files with filenames in R
问题描述
我大约有一百个excel文件,我需要将它们导入到R中并合并.所有的excel文件都有四列,每列都需要导入.这些文件如下图所示:
I have about one hundred excel files which I need to import to R and merge. All excel-files have four columns and each one needs to be imported. The files look like one below:
1 127 122
1 87
2 107
1 136 k
1 210
我还需要为每行添加文件名作为第五列.所有的excel文件都在同一个文件夹中.
I also need to add filename as fifth column for each row. All excel files are in the same folder.
到目前为止,我已经尝试过以下操作:
So far I have tried following:
library(xlsx)
setwd("c:/temp/")
filenames <- list.files(pattern=".xls")
do.call("rbind", lapply(filenames, function(x) read.xlsx(file=x, sheetIndex=1, colIndex=(1:4), header=FALSE, FILENAMEVAR=x)))
我收到以下错误:rbind(deparse.level,...)中的错误:参数的列数不匹配
I get following error: Error in rbind(deparse.level, ...) : numbers of columns of arguments do not match
我将问题定位在第三列和第四列的空白单元格中,因为如果我仅将其限制在第一列和第二列中,则函数可以正常工作.
I have located the problem to empty cells in third and fourth columns as function works perfectly if I limit it only to first and second columns.
推荐答案
我自己解决了这个问题.关键是使用rbind.fill
代替rbind
.
Figured it out myself. The key was to use rbind.fill
instead of rbind
.
library(plyr)
df.list <- lapply(filenames, function(x) read.xlsx(file=x, sheetIndex=1,
colIndex=1:4,as.data.frame=TRUE, header=FALSE, FILENAMEVAR=x))
final.df <- rbind.fill(df.list)
这篇关于在R中导入多个具有文件名的Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!