Re: [R] Nesting Functions

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
Date: Sat 28 Jan 2006 - 14:29:43 EST

On 1/27/2006 9:07 PM, Manuel Morales wrote:
> 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?

Something like this would work:

nest <- function(f, initial, reps) {

      result <- initial
      for (i in seq(len=max(reps))) result <- ifelse(i <= reps,
					            f(result), result)
      result

  }

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 Sat Jan 28 14:44:02 2006

This archive was generated by hypermail 2.1.8 : Sat 28 Jan 2006 - 20:12:09 EST