Re: [R] I really don't understand functions in R :-)

From: Thomas Lumley <tlumley_at_u.washington.edu>
Date: Fri 20 Oct 2006 - 16:49:20 GMT

On Fri, 20 Oct 2006, Alberto Monteiro wrote:

> An example:
>
> n <- 3
> f <- function(x) x^n
> f(2)
> # [1] 8
> n <- 2
> f(2)
> # [1] 4
> f
> # function(x) x^n
>
> Ok, I know this is trivial, because function f is foverer bound
> to the variable n. But how can I _fix_ n when I define _f_, so
> that changing _n_ won't change the function f?

You need to make sure that n is stored inside the function. One approach is to write a function that makes functions like f():

> make.f<-function(n) {function(x) x^n}
> n<-2
> f2<-make.f(n)
> n<-3
> f3<-make.f(n)
> f2(2)

[1] 4
> f3(2)

[1] 8

f2() and f3() each have a private copy of n from their enclosing environment.

         -thomas



R-help@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. Received on Sat Oct 21 02:59:31 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 20 Oct 2006 - 17:30:11 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.