From murdoch at stats.uwo.ca  Fri Feb 23 20:01:56 2007
From: murdoch at stats.uwo.ca (Duncan Murdoch)
Date: Fri, 23 Feb 2007 14:01:56 -0500
Subject: [Rd] Functions that write functions in R packages
In-Reply-To: <f8e6ff050702230805s2c45957epe516e5b431a7cdd2@mail.gmail.com>
References: <f8e6ff050702230805s2c45957epe516e5b431a7cdd2@mail.gmail.com>
Message-ID: <45DF3A24.1080607@stats.uwo.ca>

On 2/23/2007 11:05 AM, hadley wickham wrote:
> Dear all,
> 
> Another question related to my ggplot package:  I have made some
> substantial changes to the backend of my package so that plot objects
> can now describe themselves much better.  A consequence of this is
> that a number of convenience functions that previously I wrote by
> hand, can now be written automatically.  What is the best practice for
> creating these functions for bundling in a package?  I see three
> possible solutions:
> 
>  * dump function specifications out to a .r file
>  * dynamically create at package build time so they are including in
> the package rdata file
>  * dynamically create at package load time
> 
> Can anyone offer any advice as to which is preferable? (or if there's
> a better way I haven't thought of)
> 
> My code currently looks like this (experimenting with two ways of
> creating the functions)
> 
> create_accessors <- function(objects, name, short=NULL) {
> 	lapply(objects, function(x) {
> 		assign(paste(name, x$objname, sep="_"), x$new, pos=globalenv())
> 		if (!is.null(short)) {
> 			eval(
> 				substitute(
> 					f <- function(plot, ...) plot + add(...),
> 					list(
> 						add = as.name(paste(name, x$objname, sep="_")),
> 						f = as.name(paste(short, x$objname, sep=""))
> 					)
> 				), envir = globalenv()
> 			)
> 				
> 		}
> 	})		
> }

I'd say it's not a great idea to write to globalenv.  What if your 
function stomps on my object of the same name?  It would be better to 
set up your own environment and write these objects there.  You could 
then attach that environment, and the user would see your functions (if 
he hadn't defined his own).

If others of your functions need to call these, then you need to be 
careful with environments so that they don't accidentally call the 
user's function of the same name instead.

With the considerations above, I think it would be easiest to do the 
creation at install time or earlier, rather than at load time.

Duncan Murdoch



[Rd] Functions that write functions in R packages
Duncan Murdoch