Julio Sergio
2013-Jun-05 02:53 UTC
[R] Trying to build up functions with its names by means of lapply
I want to generate specific gamma distribution functions, given fixed parameters. This is I have k, and theta, say k <- 32.2549 # shape theta <- 26.32809 # scale # I have an auxiliary function that produces funcions according to # a given character (this is to have either dgamma, pgamma or qgamma) # for the specific parameters given above: faux <- function(c) { function (x) get(paste0(c,"gamma"))(x,k,scale=theta) } # So I can have, for instance, dgamma, and pgamma with dff <- faux("d") pff <- faux("p") dff(1000) ## [1] 0.001433138 pff(1000) ## [1] 0.844305 Now, if I try to produce both functions in one shot with lapply, the thing doesn't work, see ffs <- lapply(c("d", "p"), faux) ffs[[1]](1000) ## [1] 0.844305 ffs[[2]](1000) ## [1] 0.844305 The two produced functions are the very same and correspond to pgamma!! Maybe I'm missing something. Do you have any idea? Thanks, -Sergio.
Michael Weylandt
2013-Jun-05 06:13 UTC
[R] Trying to build up functions with its names by means of lapply
On Jun 5, 2013, at 3:53, Julio Sergio <juliosergio at gmail.com> wrote:> I want to generate specific gamma distribution functions, given fixed > parameters. > This is I have k, and theta, say > > k <- 32.2549 # shape > theta <- 26.32809 # scale > > > # I have an auxiliary function that produces funcions according to > # a given character (this is to have either dgamma, pgamma or qgamma) > # for the specific parameters given above: > > faux <- function(c) { > function (x) get(paste0(c,"gamma"))(x,k,scale=theta) > } > > # So I can have, for instance, dgamma, and pgamma with > > dff <- faux("d") > pff <- faux("p") > > dff(1000) > ## [1] 0.001433138 > > pff(1000) > ## [1] 0.844305 > > Now, if I try to produce both functions in one shot with lapply, the thing > doesn't work, see > > ffs <- lapply(c("d", "p"), faux) > > ffs[[1]](1000) > ## [1] 0.844305 > > ffs[[2]](1000) > ## [1] 0.844305 > > The two produced functions are the very same and correspond to pgamma!! > Maybe I'm missing something. Do you have any idea?I think you are hitting a bit of strangeness R generously calls 'lazy evaluation'. I'm afraid I don't have a reference at hand, but search the archives for mention of the promise mechanism. MW> > Thanks, > > -Sergio. > > ______________________________________________ > R-help at r-project.org mailing list > 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.