1

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.

  • 3
    `"sheet_name"` is a string, it does not change. `sheet_name` is a variable, which a user will set to a string such as `"sales"` or `"profit"`. Use `sheet_name` in side your function, without quotes. And call your function with a string argument, `read_fun("sales")`. – Gregor Thomas Nov 08 '17 at 15:08

1 Answers1

1

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.

cparmstrong
  • 749
  • 5
  • 21
  • Hi Seeellayewhy, This lapply function works fine. But one further question, how could i do the automatically split the list into different data frame, and assign the corresponding name? – bihappywater Nov 10 '17 at 05:25