r - Attaching object without using attach() or with() -


this may appear strange request, i'm looking attach object temporarily individual elements can extracted said object, without using attach() or with(). instance, i'm aware these 2 approaches fine index data.frame elements name"

obj <- data.frame(n=2, sd=1)  myfun <- function(obj){     n2 <- obj$n^2     rnorm(n2, obj$sd) } myfun(obj)  myfun2 <- function(obj){     with(obj, {         n2 <- n^2         rnorm(n2, sd)     }) } myfun2(obj) 

however, want more general, form can

# wanted myfun3 <- function(){     n2 <- n^2     rnorm(n2, sd) } with(obj, myfun3()) #this idea doesn't work 

so explicitly indexing elements of obj not required, , wrapping whole statement in with() function can avoided. myfun3() doesn't locate internals of obj, to. following works fine , want functional standpoint, far kosher:

attach(obj) myfun3() detach(obj) 

attaching considered bad, , purpose code has work within r package, attach() isn't allowed (as well, nested within function can run in parallel....so exporting global environment not solution).

ultimately, work follows in safe parallel computing environment

library(parallel) cl <- makecluster() parfun <- function(index, obj, myfun){     out <- with(obj, myfun())     out }     parsapply(cl=cl, 1:100, parfun, obj=obj, myfun=myfun3) 

any thoughts appreciated.

how about:

do.with  <-  function(context,fun,args=list()){     env  <-  as.environment(context)     parent.env(env)  <-  environment(fun)     environment(fun)  <- env     do.call(fun,args) }  context = list(x=1,y=2) add = function() x + y do.with(context,add)   context = list(x=2) parameters = list(y=5) mult = function(y) x * y do.with(context,mult,parameters) 

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -