Re: [R] Nesting Functions

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
Date: Fri 27 Jan 2006 - 13:55:05 EST

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



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 Received on Fri Jan 27 14:03:30 2006

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:42:14 EST