I have a situation where I have a function whose environment I want to change. This function is in a local custom R package.
Here's my setup. I have an R package project called testpkg with one function in /R called do_stuff.R:
#' A function that clearly does stuff
#' @export
do_stuff <- function() {
Sys.sleep(1)
"Done"
}
In an interactive script I'm trying to assign this function to another environment. I want to use theĀ assign function so I can do this programmatically. Here's what I've been trying:
devtools::load_all()
env <- new.env()
assign("do_stuff", do_stuff, env)
# See if it worked (nope, environment is namespace:testpkg)
> env$do_stuff
# function() {
# Sys.sleep(1)
# "Done"
# }
# <environment: namespace:testpkg>
If I use environment()<- it does seem to work:
devtools::load_all()
environment(do_stuff) <- new.env()
# See if it worked (yes, environment is different)
> do_stuff
#function() {
# Sys.sleep(1)
# "Done"
# }
# <environment: 0x7f9d1c3a8fd8>
But this isn't ideal since I need this to work programmatically. I realize this seems like a pretty strange thing to do. Essentially, I need to make my custom functions transportable to work with the future package for async, but that's beside the point.
In R, functions are lexically scoped. This means that they look up free variables in the environment where they are defined. In order for that to work, functions need to keep track of that environment. This is the same same for both anonymous and named functions. You can retrieve/set this environment using the
envionment()andenvironment<-()functions. This is just the likeclass()andnames()functions. They alter properties of the object itself.When you use
assign(), you are just pointing a particular symbol/name to an object. Different environments may assign different values to the same name. This has nothing to do with the environment property attached to a function when it was created. A named function in one environment can easily point to a different environment to resolve free variable names.Here's a demonstration of the way things work