Reputation: 712
I have the following two functions which reads excel sheets, does some data cleaning and binds these sheets together.
library(tidyverse)
library(readxl)
read <- function(Path, Sheet){
df <- read_excel(path = Path, sheet = Sheet,
skip = 24,
na = '-')[-2, ] %>%
mutate(name = Sheet) %>%
rename_all(~str_replace_all(., "\\s+", ""))
return(df)
}
sheets <- function(number){
if(number == 1){
Sheets <- c("A", "B")
} else if(number == 2){
Sheets <- c("C","D")
} else{
warning("sheet number can only be 1 or 2")
}
s1<-read(path="Data/file1",Sheet=Sheets[1])
s2<-read(path="Data/file1",Sheet=Sheets[2])
return(rbind(s1,s2))
}
The functions work fine, but I want to update the 'sheets()' function so that it binds any number of sheets together (instead of just assuming a fixed number (2) sheets as I've done above. I am thinking of using a for loop for this but is there a better approach to do this?
Upvotes: 0
Views: 165
Reputation: 388817
You can use excel_sheets
to get all the sheets in the excel and combine them together with map_df
.
sheets <- function(path){
sheets <- readxl::excel_sheets(path)
purrr::map_df(sheets, read, Path = path)
}
result <- sheets('Data/file1')
Upvotes: 2