[R] Remembering a value in multiple calls of a function

Douglas Bates bates at stat.wisc.edu
Fri Jul 17 09:33:34 CEST 2009


On Fri, Jul 17, 2009 at 9:15 AM, Saptarshi Guha<saptarshi.guha at gmail.com> wrote:
> Hello,
> I tried this pseudo-generator style experiment (see below). The "<<-"
> operator assigns to in the calling environment which would be the
> environment of  "getN".

Yes.

> Yet when the function incr is returned, isn't this environment lost?

No.  The function getN returned a function closure so the environment
of getN is preserved as long as the object a is preserved.

> Also the print displays GlobalEnv, yet the globalenv does not have any
> mention of startgiven.

If you want to see the objects in the enclosing environment of a
function you can use

ls(environment(a))

or, perhaps more informatively,

ls.str(environment(a))

Using parent.frame, as you did, will give you the environment from
which the function was called, which in this case is the global
environment.

> This code was inspired from and old issue of RJournal , but I'm not
> sure how this works.
>
> I'm not sure how this works and an explanation would be helpful.
>
> Thank you
> Saptarshi
>
> getN <- function(start){
>  startgiven <- start;
>  incr <- function(n=NA){
>    print(parent.frame())
>    if(!is.na(n)) startgiven<<-n
>    startgiven<<-startgiven+1
>    return(startgiven)
>  }
> }
> a=getN(10)
> a() #11
> a()#12




More information about the R-help mailing list