[R] Trying to build up functions with its names by means of lapply

Rui Barradas ruipbarradas at sapo.pt
Wed Jun 5 11:49:25 CEST 2013


Hello,

If in faux we ?force the return value, the bug is gone.


faux <- function(c) {
	f <- function (x) get(paste0(c,"gamma"))(x,k,scale=theta)
	force(f)
	f
}

Hope this helps,

Rui Barradas

Em 05-06-2013 07:13, Michael Weylandt escreveu:
>
>
> 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.
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list