使用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屋!