[R] Functions returning functions
Paulo Grahl
pgrahl at gmail.com
Wed May 20 14:00:34 CEST 2009
Thanks a lot !
regards,
Paulo Gustavo Grahl, CFA
On Wed, May 20, 2009 at 8:31 AM, Romain Francois
<romain.francois at dbmail.com> wrote:
> Paulo Grahl wrote:
>>
>> Dear All:
>>
>> I have a question regarding the behavior of functions.
>> Say I define a function that returns another function :
>> A <- function(parameters) {
>> # calculations w/ parameters returning 'y'
>> tmpf <- function(x) { # function of 'y' }
>> return(tmpf)
>> }
>>
>> The value of the parameters are stored in an environment local to the
>> function. Then I call
>> x<- something
>> B<-A(x)
>>
>> When R executes this last statement, does it perform all the
>> calculations inside function A again
>
> no, see this:
>
>> f <- function( x = 3){
> + function( ){}
> + }
>> g <- f()
>> ls.str( environment(g) )
> x : num 3
>> h <- f(6)
>> ls.str( environment(h) )
> x : num 6
>> ls.str( environment(g) )
> x : num 3
>
> See also colorRampPalette which uses this feature:
>
>> colorRampPalette
> function (colors, ...)
> {
> ramp <- colorRamp(colors, ...)
> function(n) {
> x <- ramp(seq.int(0, 1, length.out = n))
> rgb(x[, 1], x[, 2], x[, 3], maxColorValue = 255)
> }
> }
> <environment: namespace:grDevices>
>> pal <- colorRampPalette( c("blue", "white", "red") )
>> pal
> function (n)
> {
> x <- ramp(seq.int(0, 1, length.out = n))
> rgb(x[, 1], x[, 2], x[, 3], maxColorValue = 255)
> }
> <environment: 0x99aba4c>
>> ls.str( environment( pal ) )
> colors : chr [1:3] "blue" "white" "red"
> ramp : function (x)
>>
>> (i.e., all the calculations that
>> yield 'y')
>> or the value of 'y' is already stored in the function's local environment
>> ?
>>
>> Many thanks.
>> Paulo Gustavo Grahl, CFA
>>
>
> --
> Romain Francois
> Independent R Consultant
> +33(0) 6 28 91 30 30
> http://romainfrancois.blog.free.fr
>
>
>
More information about the R-help
mailing list