0

I'm trying to use the assign() function to use one of my inputs as part of the dataframe returned by a UDF I created, but it doesn't work. There are no errors, but the dataframe created within the UDF is not stored in my global environment. My code is similar to as follows:

read_report <- function(id) {
  assign(paste0("extract_", id),
         read_excel(path = 
                      paste0(path, "_", id, ".xlsx"), 
                    sheet = 1
         )
  )
}

It works well enough outside the function, so I'm not sure what I'm doing wrong. When I run read_report(1022) for example, I don't get a dataframe named extract_1022. I've also tried putting return(paste0("extract_",id)) at the end to no avail.

Any and all help appreciated! Thanks :)

Lasmyr
  • 39
  • 4

1 Answers1

0

Specify the environment in assign because by default the object is created in the local environment of the function which cannot be accessed outside the function.

read_report <- function(id) {
    assign(paste0("extract_", id), 
        readxl::read_excel(path = paste0(path, "_", id, ".xlsx"), sheet = 1), 
        envir = .GlobalEnv)
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213