【问题标题】:Importing multiple .xlsx files with multiple sheets in R在 R 中导入具有多个工作表的多个 .xlsx 文件
【发布时间】:2021-12-23 20:12:54
【问题描述】:

在 R 中导入具有多个工作表的多个 .xlsx 文件时出现问题。 我有 6 个 Excel 文件,每个文件有 5 个不同的工作表(它们的长度都相同)。 我希望将它们作为以下列表形式导入 R:

[[1]][[1]]
[[2]][[1]]
[[3]][[1]]
[[4]][[1]]
[[5]][[1]]
[[6]][[1]]
[[2]][[1]]
[[2]][[2]]
[[2]][[3]]
.
.
.
[[6]][[5]]

第一个列表对应于特定的 Excel 文件,第二个对应于工作表。 所以,第一个 [[1]][[1]] 是第一个 Excel 文件的第一个工作表。

我写了以下代码

path_ <- "~/Desktop/my_folder/"

#This is suppose to read all the Excel-files
file.list <- list.files(path = paste(path_), pattern='*.xlsx', full.names = TRUE)
df.list <- lapply(file.list, function (x)  read_xlsx(x))

但它只返回六个 Excel 文件中每一个的第一个工作表。

[[1]]
[[2]]
[[3]]
[[4]]
[[5]]
[[6]]

我不知道如何让它工作。 有人可以帮我解决这个问题吗?

【问题讨论】:

  • 您需要指定要阅读的工作表。根据在线文档:“要读取的工作表工作表。字符串(工作表的名称)或整数(工作表的位置)。如果工作表是通过范围指定的,则忽略。如果两个参数都没有指定工作表,默认为第一张纸。”
  • 使用Map,或者如果你喜欢tidyverse,使用map2。一个参数是文件,另一个参数是read_excel 或read_xlsx 的工作表编号。

标签: r excel xlsx readxl


【解决方案1】:

让我们有 2 个文件,每个文件有两个工作表:

library(tidyverse)
library(readxl)

list.files("~/data", full.names = TRUE)
#> [1] "/home/rstudio/data/data.xlsx"  "/home/rstudio/data/data2.xlsx"
read_excel("/home/rstudio/data/data.xlsx", sheet = 1)
#> # A tibble: 2 x 2
#>   a       `1`
#>   <chr> <dbl>
#> 1 b         2
#> 2 c        NA
read_excel("/home/rstudio/data/data.xlsx", sheet = 2)
#> # A tibble: 2 x 2
#>   d       `4`
#>   <chr> <dbl>
#> 1 e         5
#> 2 f         6


expand_grid(
  file = list.files("~/data", full.names = TRUE),
  sheet = seq(2)
) %>%
  transmute(data = file %>% map2(sheet, ~ read_excel(path = .x, sheet = .y))) %>%
  pull(data)
#> [[1]]
#> # A tibble: 2 x 2
#>   a       `1`
#>   <chr> <dbl>
#> 1 b         2
#> 2 c        NA
#> 
#> [[2]]
#> # A tibble: 2 x 2
#>   d       `4`
#>   <chr> <dbl>
#> 1 e         5
#> 2 f         6
#> 
#> [[3]]
#> # A tibble: 2 x 2
#>   a       `1`
#>   <chr> <dbl>
#> 1 b         2
#> 2 c        NA
#> 
#> [[4]]
#> # A tibble: 2 x 2
#>   d       `4`
#>   <chr> <dbl>
#> 1 e         5
#> 2 f         6

由reprex package (v2.0.1) 于 2021 年 11 月 11 日创建

【讨论】:

    猜你喜欢
    • 2018-11-23
    • 2018-07-09
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    相关资源
    最近更新 更多