[R] Function that operates on functions: it's ok, but the display isn't

Duncan Murdoch murdoch at stats.uwo.ca
Tue Oct 10 22:12:04 CEST 2006


On 10/10/2006 3:53 PM, Alberto Monteiro wrote:
> The following code works fine:
> 
> # g is the function that returns the square of a number
> g <- function(y) y^2
> 
> # f1 is a function that takes one function
> # as argument, and returns another function
> f1 <- function(f) function(x) f(x+1) - f(x)
> 
> # h(x) is g(x+1) - g(x) or 2x + 1
> h <- f1(g)
> 
> # h(1) = 3
> # h(2) = 5
> # h(3) = 7
> 
> So far, so good. But why:
> 
> h
> 
> shows:
> 
> function(x) f(x+1)-f(x)
> <environment: 0264BE84>
> 
> I don't get it. h should show function(x) g(x+1)-g(x)
> or something like that.

But you defined the result of f1 to be function(x) f(x+1) - f(x), so 
what it is showing you is correct.  This will be evaluated in 
<environment: 0264BE84>, where f is defined to be function(y) y^2, which 
is why h gives the right answers.

Remember that R isn't a macro language, function calls aren't text 
substitutions.

Duncan Murdoch

> 
> Alberto Monteiro
> 
> ______________________________________________
> R-help at stat.math.ethz.ch 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