简体   繁体   English

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

[英]reading excel files into a single dataframe with readxl R

I have a bunch of excel files and I want to read them and merge them into a single data frame. 我有一堆Excel文件,我想读取它们并将它们合并到一个数据框中。 I have the following code: 我有以下代码:

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

to read each excel file into data frames 将每个Excel文件读入数据框

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)
}

I would do this using plyr : 我会使用plyr做到这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))
}

I would recommend to use the list enviourment in R, assign can be quite confusing and you can't determain values with GET. 我建议在R中使用列表环境,assign可能会造成混乱,并且您不能使用GET来确定值。

Should look like this: 应该看起来像这样:

l <- list()

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

ltogether <- do.call("rbind",l)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM