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

问题描述:

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

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为您提供文件中工作表的名称。你不必知道有多少。然后你命名这些表。在每张纸上迭代后,用read_excel读取它。 开始时,purrr::map适用于files让我们迭代每个文件以完成上一个过程。

最后,您将获得列表的列表。您可以再次使用tidyverse包将结果放入您想要处理的表单中。

你可以在readxl website workflow page