使用readxl R将Excel文件读取到单个数据帧中

使用readxl R将Excel文件读取到单个数据帧中

问题描述:

我有一堆Excel文件,我想读取它们并将它们合并到一个数据框中.我有以下代码:

I have a bunch of excel files and I want to read them and merge them into a single data frame. I have the following code:

library(readxl)
files <- list.files()
f <- list()
data_names <- gsub("[.]xls", "", files)

将每个excel文件读入数据框

to read each excel file into data frames

for (i in 1:length(files)){
 assign(data_names[i], read_excel(files[i], sheet = 1, skip = 6))
 }

但是,如果我尝试将其保存在变量中,只需保存最后一个文件

but, if I try to save it in a variable, just saved the last file

for (i in 1:length(files)){
 temp <- read_excel(files[i], sheet = 1, skip = 6)
}

我会使用 plyr :

library(readxl)
library(plyr)
files <- list.files(".", "\\.xls")
data <- ldply(files, read_excel, sheet = 1, skip = 6)

如果要添加带有文件名的列,则可以执行以下操作:

If you wanted to add a column with the file name, you could instead do:

data <- ldply(files, function(fil) {
  data.frame(File = fil, read_excel(fil, sheet = 1, skip = 6))
}