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 :)

1
  • 1
    Please read the comments in the linked post, this is a bad practice. Commented Jun 25, 2020 at 7:11

1 Answer 1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.