environment variables - Resuming stopped evaluation in R with correct search path -
i have function within loaded library stops evaluation on arguments using substitute function. function calls within same library, calls function library, , forth, until several calls later when want evaluated initial argument in original environment in provided. problem have search path functions in loaded libraries includes namespace::base
before global environment. example, let's foo
, bar
both functions in library lib
. such, environment in defined namespace::lib
. consider following:
> require(lib) > foo function (x) { x <- substitute(x) bar(x) } <environment: namespace:lib> > bar function (x) { eval(x) } <environment: namespace:lib> > length = 2 > foo(length) function (x) .primitive("length")
because bar
function within loaded library, searches namespace::base
first , finds above. however, if bar
defined user in interactive session, have returned 2
. looking way cause these functions behave if never halted evaluation, in case 2
returned regardless of environment in functions defined.
i can't use mget
evaluate length
starting @ .globalenv
because following not work:
> baz = function() + { + length <- 3 + foo(length) + } > baz() function (x) .primitive("length")
i instead add argument involved functions tracks how many frames ago evaluation halted. however, pretty messy , not ideal.
i call sys.function
inside last function, bar
, , trace way through previous calls , evaluate argument in environment above function halted evaluation. example, if call sys.function(1)
within body of bar
after calling foo(length)
following:
function (x) { eval(x) }
this indeed identical foo
. can use eval
sys.frames
. seems more general less perfect. have know functions stop evaluation.
does have more general solution?
does adding default enviroment these function problem?
lib<-new.env() assign("foo", function(x, env=parent.frame()) { x<-substitute(x); bar(x, env) }, envir=lib) assign("bar", function(x, env=parent.frame()) { eval(x, env) }, envir=lib) attach(lib) length = 2 foo(length) # [1] 2 baz <- function() { length <- 3 foo(length) } baz() # [1] 3 bar(expression(baz())) # [1] 3
if not, perhaps make clearer, reproducible example function calls , expected output. otherwise it's unclear having trouble.
Comments
Post a Comment