Skip to content
Prev 395387 / 398502 Next

Dynamically create a (convenience) function in a package

Hi,

n a package, I have a data object with attributes, and I want to 
dynamically create a convenience function to access those attributes. 
This way, instead of using attr(x, "number"), I would like to use number(x).



Because I don't know in advance which attributes the data object may 
have, I've used the following algorithm:

x <- structure(pi, number=exp(1))

a <- attributes(x)

for (n in names(a)) {

   if (!exists(n, mode="function")) {

     f <- eval(parse(text=sprintf("function(x) { attr(x, '%s') } ", n))) 


     assign(n, f, envir=.GlobalEnv)

   }

}

number(x)

However, I believe modifying the global environment with this is not 
allowed by CRAN for a package. Is there a way to implement such 
functionality?

Thanks Sigbert