rexcelreadxl

How to import multiple excel sheets with tabs named in numeric only in R


I have an excel workbook with 100s of sheets with tab named as strings (sheet1, R Import, etc.) and numeric (123, 456, etc.). But I want to import all the sheets for which the tab names are in numeric only. I have the following code to import all sheets but not sure how to import just the sheets with numeric tab names only:

read_excel_allsheets <- function(filename) { 
  sheets <- readxl::excel_sheets(filename) 
  x <- lapply(sheets, function(X) readxl::read_excel(filename, sheet = X)) 
  names(x) <- sheets 
  x 
}

I want to perform this operation in R. Any help would be much appreciated. Thanks!


Solution

  • I would do it this way.

    sheets <- readxl::excel_sheets('file.xlsx')
    
    xlist <- lapply(
        grep('^\\d+$', sheets, value = TRUE),
        readxl::read_xlsx,
        path = 'file.xlsx'
    )