Re: [R] how to store recursive results

From: Thomas Lumley <>
Date: Fri 22 Sep 2006 - 16:19:34 GMT

On Fri, 22 Sep 2006, X.H Chen wrote:

> Hi Gabor,
> Thanks for pointing out this for me. However, what I try to get is how to
> construct such form a function f that
> ret<-f(...),
> where ret contains the each recursive result from f, and meantime f consists
> of no <<- operator. Do you have any idea how to implemet this. Thanks a lot
> for your suggestions.

It depends on the situation. You can always pass the results back in a list or vector, eg


 	           if (n==0)
                    else c(1, n*cumfactorial(n-1))

If you want to get the results out then you have to either accumulate and return them like this or use <<-, since return() and <<- are the only ways to get results out of a function. As long as you don't use <<- to assign to variables outside the function it is a perfectly reasonable thing to do

If you were doing something like a Fibonacci sequence then assigning would be preferable

               if (m<=2) return(1)
           sapply(ls(envir=memo),get, envir=memo)

since the memoization converts the algorithm from exponential time to linear time. mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Sat Sep 23 02:27:38 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 22 Sep 2006 - 17:30:19 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.