0

大家晚安:

我正在尝试导入 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")))
}
4

2 回答 2

0

尝试使用这个:

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)
于 2020-04-17T01:01:19.613 回答
0

我们可以在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)
于 2020-04-17T01:07:37.973 回答