从电子表格中读取不同数量的表单

我使用以下代码将一系列电子表格读入R.但是,我发现即使所有电子表格中的数据共享相同的标题和结构,某些电子表格也有多个表单。 例如,在一个电子表格中,有两个表单,每个表单都包含一些数据。 我的问题是如何修改我的代码,以读取所有工作表中的数据,而无需打开每个电子表格来查找其中有多less工作表。 谢谢。

library(readxl) files <- Sys.glob("*.xlsx") files PL <- read_excel(files[1], col_names=TRUE) for(i in 2:length(files)){ x <- read_excel(files[i], col_names=TRUE) PL <- rbind(PL, x) print(i) } 

你可以使用readxl包的函数excel_sheets

 > library(readxl) > sheets <- excel_sheets("xlsx_datasets.xlsx") > sheets [1] "iris" "mtcars" "chickwts" "quakes" > x <- read_excel("xlsx_datasets.xlsx", sheet=sheets[1]) 

也就是说,要读取您的所有文件:

 PL <- NULL for(i in 1:length(files)){ sheets <- excel_sheets(files[i]) for(sheet in sheets){ x <- read_excel(files[i], col_names=TRUE, sheet=sheet) PL <- rbind(PL, x) } } 

使用tidyverse你可以使用purrr迭代

 # you could use library(tidyverse) too which includes these two packages and more library(readxl) library(purrr) # for function map and set_names below list_xl <- map(files, ~.x %>% excel_sheets() %>% set_names() %>% map(read_excel, path = .x)) 

excel_sheet为您提供文件中工作表的名称。 你不必知道有多less。 然后你命名这些表。 在每个工作表上迭代以读取read_excel 。 一开始, purrr::map适用于files让我们迭代每个文件来完成上一个过程。

最后,你会得到一份清单。 您可以再次使用tidyverse软件包将结果以您想要处理的forms进行处理。

您可以在readxl网站工作stream程页面find一个很好的例子