[Rd] Defining environments within functions

From: Giles Hooker <gjh27_at_cornell.edu>
Date: Wed, 27 Aug 2008 21:50:58 -0400


How can I define environments within a function so that they are visible to calls to a sub-function?

I have defined an objective function,

        ProfileErr = function(params,...)

which I would like to optimize using standard routines (optim, nlminb,....) but which contains auxiliary variables which need to be updated along with params. No optimization routine in R that I have found has facilities for this.

Specifically, within ProfileErr, I need to calculate

          coefs(params,...)

This a function which requires a further optimization, and I can achieve significant efficiency gains by starting where the last optimization ended, so I would like to keep track of it.

At the command line, I get around this by

	ProfileEnv = new.env()
	assign('coefs',coefs,3,ProfileEnv)

and within ProfileErr, I can call

	startcoefs = get('coefs',envir=ProfileEnv)
	* do the optimization to get newcoefs *
	assign('coefs',newcoefs,3,ProfileEnv)

Then calling

        optim(pars,ProfileErr,....)

works fine. However, when I try to wrap all of that in its own function

	profile.estimate = fn(pars,...){
		ProfileEnv = new.env()
		assign('coefs',coefs,3,ProfileEnv)
	
		res = optim(pars,ProfileErr,....)
	}


ProfileErr no longer sees ProfileEnv. I haven't been able to make much sense out of the documentation on environments, but is there a way to make this work? Otherwise I'm back to writing variables out to files.

Many thanks,

Giles

--

Giles Hooker
Assistant Professor:

Department of Biological Statistics and Computational Biology Department of Statistical Science
1186 Comstock Hall
Cornell University
Ithaca, NY, 14853

Ph: (+1 607) 255 1638
Fax: (+1 607) 255 4698

Email: giles.hooker_at_cornell.edu

--

Giles Hooker
Assistant Professor:

Department of Biological Statistics and Computational Biology Department of Statistical Science
1186 Comstock Hall
Cornell University
Ithaca, NY, 14853

Ph: (+1 607) 255 1638
Fax: (+1 607) 255 4698

Email: giles.hooker_at_cornell.edu



R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Thu 28 Aug 2008 - 10:12:36 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 29 Aug 2008 - 12:38:14 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.

list of date sections of archive