[R] Nesting Functions

Manuel Morales mmorales at williams.edu
Sat Jan 28 03:07:48 CET 2006


On Thu, 2006-01-26 at 21:55 -0500, Duncan Murdoch wrote:
> On 1/26/2006 9:45 PM, Manuel Morales wrote:
> > Dear list members,
> > 
> > I'm looking for a way to write "nested" functions similar to the
> > function "Nest" or "NestList" in Mathematica.
> > 
> > E.g.,
> > 
> > f<-function(x) x+2*x
> > 
> > f(f(f(2)))
> > 
> > might instead be written as nest(f, 2, 3)
> > 
> > read as, nest function f 3 times with 2 as the initial value.
> 
> It's easy enough using a for loop:
> 
> nest <- function(f, initial, reps) {
>     result <- initial
>     for (i in seq(len=reps)) result <- f(result)
>     result
> }
> 
> Duncan Murdoch
That works, thanks! But what if I want to apply the function to a set of
vectors.

init.values<-c(3,10,20)
rep.values<-c(0,1,2)

nest(f,init.values,rep.values) fails because only the first value is
used in a for loop. The following works, but it's clunky and doesn't
scale with variation in the number of reps.

nest.vectorize<-function(f, initial, reps)
    ifelse(reps==0,initial,
    ifelse(reps==1,f(initial),f(f(initial))))

nest.vectorize(f,init.values,rep.values)

Any suggestions?

Thanks again,

Manuel




More information about the R-help mailing list