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

jim holtman jholtman at gmail.com
Fri Oct 20 18:48:07 CEST 2006


It sounds like you want to use 'local' to create private variables:


> # your example
> n <- 3
> f <- function(x) x^n
> f(2)
[1] 8
> n<-1
> f(2)
[1] 2
> # now using 'local' to make 'n' private
> f <- local({
+ n <- 3
+ function(x) x^n
+ })
> f(2)
[1] 8
> n <- 1
> f(2)
[1] 8
>

Or why not just pass 'n' to the function

On 10/20/06, Alberto Monteiro <albmont at centroin.com.br> 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?
>
> 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.
>


-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list