Reputation: 11
I would like to cite the variable name as a string in a function, but couldn't achieve it.
For example, in one excel, i have 4 worksheets, i need to use the following line 4 times,
sales.df<- read_xlsx("abc.xlsx", sheet ="sales")
profit.df<- read_xlsx("abc.xlsx", sheet ="profit")
revenue.df<-read_xlsx("abc.xlsx", sheet ="revenue")
budget.df<- read_xlsx("abc.xlsx", sheet ="budget")
Instead, I want to write a function:
read_func = function(sheet_name){
sheet_name.df<- read_xlsx("abc.xlsx", sheet ="sheet_name"))
return(sheet_name.df)
}
The call the function
read_func(sales)
Unfortunately, it doesn't work. The sheet_name is not dynamically updated.
Thank you in advance for your kind help.
Upvotes: 1
Views: 73
Reputation: 819
The readxl
package has a function excel_sheets()
to read all sheets in a file, which you can use with lapply
to accomplish the same thing.
library(readxl)
lapply(excel_sheets("abc.xlsx"), read_excel, path = "abc.xlsx")
It is a part of the tidyverse so you can read more on it there.
Upvotes: 1