Home » excel » How to read multiple excel sheets in R programming?

How to read multiple excel sheets in R programming?

Posted by: admin March 9, 2020 Leave a comment

Questions:

I have an excel file which contains 400 sheets. How can I load this excel file to R using read.xls function? Please provide sample code for this.

How to&Answers:

I’m just assuming you want it as all one data.frame() and that all the sheets contain the same data.

library(xlsReadWrite) 
sheets <- c("Sheet 1","Sheet 2", "Sheet 3")

df <- data.frame()

for (x in 1:400) 
df <- rbind(df, read.xls("filename.xls", sheet=sheets[x]))
}

If each sheet is it’s own unique data.frame() you’ll probably want to put them in a list. Otherwise you can use assign() if you want them as objects in the environment.

sheet_list <- list()
for(x in 1:400) {
sheet_list[[x]] <- read.xls("filename.xls", sheet=sheets[x])
} 

Or, without a for loop:

sheet_list <- lapply(sheets, function(x) read.xls("filename.xls",sheets=x))