I am working on a project. The document is an excel document with multiple sheets. I have imported my data but I am trying to tell R to read all the sheets in the excel document. Below is the code i used.
Thanks for posting about this situation - it is very common!
One approach (you have likely already considered) is to simply run multiple import() commands to import the sheets one at a time, saved as distinct data frames:
# load {rio} package to import data
pacman::p_load(rio)
# run separate `import()` commands for each sheet
sheet1 <- import("Interactive Map - Surveillance - STI.xlsx", sheet = "sheet1name")
sheet2 <- import("Interactive Map - Surveillance - STI.xlsx", sheet = "sheet2name")
sheet3 <- import("Interactive Map - Surveillance - STI.xlsx", sheet = "sheet3name")
Assuming that the data in each sheet is stored in the same format, and that you want to combine them into one dataframe… there is another option that involves iteration with the {purrr} package and is described in this section of the Epi R Handbook:
# load packages
pacman::p_load(readxl, purrr, tidyverse)
# extract the sheet names and save them as sheet_names
sheet_names <- readxl::excel_sheets("Interactive Map - Surveillance - STI.xlsx")
# pass these names through the import() function one at a time, combine the imported sheets into one data frame, with a new column that contains the sheet of origin
# begin with sheet names
combined <- sheet_names %>%
# set their names
purrr::set_names() %>%
# iterate, import, save in list
map(.f = ~import("Interactive Map - Surveillance - STI.xlsx", which = .x)) %>%
# combine list of data frames, preserving origin sheet in new column
bind_rows(.id = "origin_sheet")
You should now have one data frame containing all the data, with a column containing the sheet of origin!