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

Iris Simmons |kw@|mmo @end|ng |rom gm@||@com
Mon Oct 30 11:37:04 CET 2023


If you don't know the name of the attributes in advance, how can you know
the function name to be able to call it? This seems like a very flawed
approach.

Also, I would discourage the use of eval(parse(text = )), it's almost
always not the right way to do what you want to do. In your case,

eval(bquote(function(x) attr(x, .(n))))

would be better.


On Mon, Oct 30, 2023, 06:28 Sigbert Klinke <sigbert using wiwi.hu-berlin.de>
wrote:

> 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
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list