[R] dynamics of functions

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Thu Jun 5 17:57:46 CEST 2003


Hotz, T. wrote:

> What about the following function?
> 
> iterate<-function(f,n,x){
>   if(n==0) return(x)
>   y<-x
>   for(i in 1:n)y<-f(y)
>   y
> }
> iterate(sqrt,3,256)
> 

  Or the following:

iterFun <-
   function(f,n,x,...){
     if(n==0){return(x)}
     for(i in 1:n){
       x<-f(x,...)
     }
     return(x)
   }

  If you want to construct an arbitrary function without naming it, you 
can do something like this:

 > iterFun(function(z){3.9*z*(1-z)},121,.6)
[1] 0.6449397

  And the ... part means you can try different constants in your function:

 > iterFun(function(z,a){a*z*(1-z)},121,.6,a=3.9)
[1] 0.6449397
 > iterFun(function(z,a){a*z*(1-z)},121,.6,a=3.901)
[1] 0.09416016
 > iterFun(function(z,a){a*z*(1-z)},121,.6,a=3.900001)
[1] 0.7612195

  Fun with functions.

Baz




More information about the R-help mailing list