[R] how to write a function that remembers its state across its calls

Greg Snow Greg.Snow at imail.org
Mon Feb 1 19:37:26 CET 2010


Use "local" to create a local environment and save your information there:

> f <- local( {
+ xx <- rep(NA,3)
+ function(x) {
+ xx <<- c(xx[-1],x)
+ mean(xx)
+ } } )
> 
> f(1)
[1] NA
> f(2)
[1] NA
> f(3)
[1] 2
> f(4)
[1] 3
> 
> xx
Error: object 'xx' not found
>

Hope this helps,

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Hao Cen
> Sent: Monday, February 01, 2010 9:26 AM
> To: r-help at r-project.org
> Subject: [R] how to write a function that remembers its state across
> its calls
> 
> Hi,
> 
> I wonder how to write a function that remembers its state across its
> calls. For example, I would like to compute the average of the pass
> three
> values the function has seen
> 
>  f(1)  # NA
>  f(2)  # NA
>  f(3)  # 2
>  f(4)  # 3
> 
> This would require f to keep track of the values it has seen. In other
> languages like c++ or java it is easy to do by having a member
> variable. I
> am not sure how to do similar things in R because the variables
> declared
> in functions are gone after the function exits.
> 
> It is possible do a quick-dirty function by declaring a variable
> outside
> of f to keep track of what the function has seen. But then the logic of
> keeping tracking that variable is not encapsulated in f. It would be
> messy
> if I have lots of such functions.
> 
> Thanks for any advice in advance.
> 
> Jeff
> 
> ______________________________________________
> 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