I am trying to split excel file with multiple sheets to a new file based on prefix in sheet name.
I would like to output all sheets with prefix a_ to a.xslx , b_ to b.xslx and so on
Here is the code so far:
library(readxl)
library(readr)
library(writexl)
#get sheet names
sheets <- excel_sheets("/path/to/excel/file")
filenames <- paste0(sheets, ".xslx")
#sheet prefix
m <- regexpr("^.*_", filenames)
file_prefix <- unique(regmatches(filenames, m))
prefnames <- paste0(file_prefix, ".xslx")
#read_excel - sheets with same prefix
datspref <- lapply(file_prefix, read_excel, path = "/path/to/excel/file")
#save sheets with same prefix to a new excel file
lapply(seq_along(dats), function(i) write_xlsx(dats[[i]], prefnames[i]))
Appreciate any help!
Setup: I made
sample.xlsx
with the following sheets (and the same 2x2 table on each sheet):FYI: if you need to remove the leading
a_
from the sheet names, just change the name ofdats
before splitting it, perhaps