# [R] how to store recursive results

Gabor Grothendieck ggrothendieck at gmail.com
Fri Sep 22 18:00:33 CEST 2006

```1. The point is that you can use <<- and still not pollute the
global environment with any variables so its not clear
why there should be any requirement not to use it.

Other possiblities are

2. to pass the info around through the return value or through an environment:

fact <- function(n) {
if (n == 1) list(n, c("1" = 1))
else {
f <- fact(n-1)
out <- list(n * f[[1]], unlist(f))
names(out[[2]])[1] <- n
out
}
}

fact(4)

3. or through an environment:

fact <- function(n, e) {
if (n == 1) e[["1"]] <- 1
else n * (e[[format(n)]] <- fact(n-1, e))
}

e <- new.env()
fact(4, e)
as.list(e)

On 9/22/06, X.H Chen <xchen_stat at hotmail.com> 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
>
> Cheer
>
> Xiaohui Chen
>
> Dept. of Statistics
>
>
>
>
> >From: "Gabor Grothendieck" <ggrothendieck at gmail.com>
> >To: "X.H Chen" <xchen_stat at hotmail.com>
> >CC: r-help at stat.math.ethz.ch
> >Subject: Re: [R] how to store recursive results
> >Date: Fri, 22 Sep 2006 06:49:22 -0400
> >
> >Note that <<- is not necessarily global:
> >
> >if (exists("x")) rm(x)
> >f <- function() {
> >       x <- 2
> >       g <- function() x <<- 3
> >       g()
> >       x
> >}
> >f() # 3
> >exists("x") # FALSE
> >
> >On 9/22/06, X.H Chen <xchen_stat at hotmail.com> wrote:
> >>Hi all,
> >>
> >>How to store recursive resutls from a function for each step without using
> >>global operators <<-? Thanks ahead.
> >>
> >>Xiaohui Chen
> >>
> >>Dept. of Statistics
> >>
> >>_________________________________________________________________
> >>Don't waste time standing in line—try shopping online. Visit Sympatico /
> >>MSN
> >>
> >>
> >>
> >>______________________________________________
> >>R-help at stat.math.ethz.ch mailing list
> >>https://stat.ethz.ch/mailman/listinfo/r-help
> >>http://www.R-project.org/posting-guide.html
> >>and provide commented, minimal, self-contained, reproducible code.
> >>
> >>
> >>
>
> _________________________________________________________________
> Buy what you want when you want it on Sympatico / MSN Shopping
> http://shopping.sympatico.msn.ca/content/shp/?ctId=2,ptnrid=176,ptnrdata=081805
>
>

```