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

Bill.Venables at csiro.au Bill.Venables at csiro.au
Fri Jul 17 09:42:14 CEST 2009


'startgiven' is in the environment of your function 'incr' (which is what your function 'a' becomes).  It might be more transparent to define your function with an enclosing local environment explicitly, for example:

> b <- local({
+   startgiven <- 0
+   function(n) {
+     if(!missing(n)) {
+       startgiven <<- n
+     } else {
+       startgiven <<- startgiven + 1
+     }
+     startgiven
+   }
+ })
> b(5)
[1] 5
> b()
[1] 6
> b()
[1] 7
> 

You should look carefully at the help information for the superassignment operator 

help("<<-")

to see precisely where assignments made by this operator are located. 


Bill Venables
http://www.cmis.csiro.au/bill.venables/ 


-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Saptarshi Guha
Sent: Friday, 17 July 2009 5:16 PM
To: R-help at r-project.org
Subject: [R] Remembering a value in multiple calls of a function

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

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list