[R] Dynamically create a (convenience) function in a package

Sigbert Klinke @|gbert @end|ng |rom w|w|@hu-ber||n@de
Mon Oct 30 11:28:10 CET 2023


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

-- 
https://hu.berlin/sk
https://www.stat.de/faqs
https://hu.berlin/mmstat
https://hu.berlin/mmstat-ar



More information about the R-help mailing list