【问题标题】:How can I Import multiple excel files with several sheets?如何使用多张工作表导入多个 excel 文件?
【发布时间】:2020-07-30 09:41:42
【问题描述】:

大家晚安:

我正在尝试导入 8 个结构相同但名称不同的 excel 文件。我有使用前 3 张纸导入一个文件的代码,但我必须重复此代码 8 次。我想创建一个函数只放一次,而且我需要知道它们来自哪里(excel文件的名称)。提前谢谢你。

library(readxl)
read_excel_allsheets <- function("path", tibble = false){
sheets <- readxl::excel_sheets("path")
sheets <- sheets[c(1,2,3)]
x <- lapply(sheets, function(X) readxl::read_excel("path", sheet = X,skip = 5))
if(!tibble) x <- lapply(x, as.data.frame)
names(x) <- sheets
x
all_data1 <- do.call(rbind, lapply(sheets, function(X) 
transform(readxl::read_excel("path", sheet = X,skip = 5), estatus = X,tipo="Corriente",enfoque="Sector")))
}

【问题讨论】:

    标签: r excel function google-sheets import


    【解决方案1】:

    试试这个:

    read_excel_allsheets <- function(path, tibble = FALSE) {
          sheets <- readxl::excel_sheets(path)
          sheets <- sheets[c(1,2,3)]
          x <- do.call(rbind, lapply(sheets, function(X) 
                  transform(readxl::read_excel(path, sheet = X,skip = 5), 
                                   estatus = X,tipo="Corriente",enfoque="Sector")))
          if(!tibble) x <- lapply(x, as.data.frame)
          names(x) <- sheets
          return(x)
    }
    
    all_data <- lapply(list.files('/path', full.names = TRUE), read_excel_allsheets)
    

    【讨论】:

    • 对不起。我不明白。我在这个路径中有 8 个 excel 文件:/Users/ladyinfante/Documents/oficina/Control de calidad/CCNN。我必须把这个放在这里吗:all_data
    • 对不起。我试图理解。我该如何放置路径?在此文件夹中:/Users/ladyinfante/Documents/oficina/Control de calidad/CCNN/test1.xlsx /Users/ladyinfante/Documents/oficina/Control de calidad/CCNN/test3.xlsx 直到 test8。谢谢
    • @LadyInfante list.files('/Users/ladyinfante/Documents/oficina/Control de calidad/CCNN', full.names = TRUE) 的输出是什么? excel文件列表?并且所有这些 excel 文件中都有多个工作表?
    • 你没有回答我问的问题。
    • 所以这确实给了你这 8 个文件,对吧? list.files('/Users/ladyinfante/Documents/oficina/Control de calidad/CCNN/', full.names = TRUE) ?如果是,则使用all_data &lt;- lapply(list.files('/Users/ladyinfante/Documents/oficina/Control de calidad/CCNN/', full.names = TRUE), read_excel_allsheets)
    【解决方案2】:

    我们可以在tidyverse这样做

    library(dplyr)
    library(purrr)
    
    read_excel_allsheets <- function(path, tibble = FALSE) {
          sheets <- readxl::excel_sheets(path)
          sheets <- sheets[c(1,2,3)]
          x <- map_dfr(sheets,  ~ .x %>%
                  mutate(readxl::read_excel(path, sheet = .x,skip = 5), 
                        estatus = .x,tipo="Corriente",enfoque="Sector")))
          if(!tibble) x <- map(x, as.data.frame)
          names(x) <- sheets
          x
    }
    
    all_data <- map(list.files('/path', full.names = TRUE), read_excel_allsheets)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 2018-07-09
      • 2021-01-27
      • 2019-11-02
      • 1970-01-01
      相关资源
      最近更新 更多