循环阅读同一工作表的多张表,并另存为单独的数据框/变量

时间:2018-11-24 20:06:13

标签: r excel

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)

1 个答案:

答案 0 :(得分:1)

我不会使用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