首页 > 解决方案 > 循环并阅读多张相同的工作表并保存为单独的数据框/变量

问题描述

install.packages("readxl")

library("readxl")

data <- read_excel("spreadsheet.xlsx")

sheets <- excel_sheets("spreadsheet.xlsx")

sheetList <- as.list(sheets) #convert sheets to list

for (s in sheetList){
  read_excel("spreadsheet.xlsx",sheet=s)
} #want to do such that when looping through each sheet, it would read in the data and be assigned its own 'variable'(dataframe)

标签: rexcel

解决方案


我不会使用 for 循环。使用 lapply 更容易遍历列表。这是我将如何做到的。

library(readxl)
sheets_to_read <- excel_sheets("spreadsheet.xlsx") ##Obtain the sheets in the workbook


list_with_sheets <- lapply(sheets_to_read,
                           function(i)read_excel("spreadsheet.xlsx", sheet = i))

names(list_with_sheets) <- sheets_to_read ##Add names

list2env(mylist ,.GlobalEnv) ##This function should put them all in the global environment

推荐阅读