nachocab
nachocab

Reputation: 14364

How do I load objects to the current environment from a function in R?

Instead of doing

a <- loadBigObject("a")
b <- loadBigObject("b")

I'd like to call a function like

loadBigObjects(list("a","b"))

And be able to access the a and b objects.

Upvotes: 1

Views: 2671

Answers (3)

Gavin Simpson
Gavin Simpson

Reputation: 174778

It is not clear what loadBigObjects() does or where it will look for a and b. How does it load the objects from file or sourcing code?

There are lots of options in general:

  • sys.source() allows an R file to be sourced to a given environment
  • load() which will load an .Rdata file to a given environment
  • assign() in combination with any object created by loadBigObjects() or a call to readRDS() can also load an object to a given environment.

From within your function, you'll want to specify the environment in which to load objects as the Global Environment by using globalenv(). If you don't do that then the object will only exist in the evaluation frame of the running loadBigObjects(). E.g.

loadBigObjects <- function(list) {
    lapply(list, function(x) assign(x, readRDS(x), envir = globalenv()))
}

(as per your comment to @GSee's Answer, and assuming the list("a","b") is sufficient information for readRDS() to locate and open the object.

Upvotes: 7

Brian Diggs
Brian Diggs

Reputation: 58825

The assign function can be used to define a variable in an environment other than the current one.

loadBigObjects <- function(lst) {
  lapply(lst, function(l) {
    assign(l, loadBigObject(l), envir=globalenv())
  }
  lst
}

(Not that this is necessarily a good idea.)

Upvotes: 2

GSee
GSee

Reputation: 49810

Without knowing anything about what loadBigObject is or does, you can use lapply to apply a function to a list of objects

lapply(list("a", "b"), loadBigObject)

If you provided the code for loadBigObject or at least describe what it is supposed to do, a better loadBigObjects function could probably be written.

Upvotes: 3

Related Questions