I am looking to import an excel workbook into R with multiple sheets. However, I can't seem to quite make this work. The code I have been using is the following:
library(XLConnect)
# Read Excel Sheet
excel <- loadWorkbook("C:/Users/rawlingsd/Downloads/17-18 Prem Stats.xlsx")
# get sheet names
sheet_names <- getSheets(excel)
names(sheet_names) <- sheet_names
# put sheets into a list of data frames
sheet_list <- lapply(sheet_names, function(.sheet){readWorksheet(object=excel, .sheet)})
# limit sheet_list to sheets with at least 1 dimension
# sheet_list2 <- sheet_list[sapply(sheet_list, function(x) dim(x)[1]) > 0]
# code to read in each excel worksheet as individual dataframes
for (i in 1:length(sheet_list)){assign(paste0("2018df", i), as.data.frame(sheet_list[i]))}
# define function to clean data in each data frame (updated based on your data)
If anyone could help me with my code or share a code that works for them, it would be greatly appreciated
You can use readxl
package. See the following example.
library(readxl)
path <- readxl_example("datasets.xls")
sheetnames <- excel_sheets(path)
mylist <- lapply(excel_sheets(path), read_excel, path = path)
# name the dataframes
names(mylist) <- sheetnames
The spreadsheet will be captured in a list with the sheetname as the name of the dataframe in the list.
If you want to bring the dataframes out of the list use the next bit of code.
# Bring the dataframes to the global environment
list2env(mylist ,.GlobalEnv)