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

Saptarshi Guha saptarshi.guha at gmail.com
Fri Jul 17 09:15:36 CEST 2009


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".
Yet when the function incr is returned, isn't this environment lost?
Also the print displays GlobalEnv, yet the globalenv does not have any
mention of startgiven.
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