[R] how to write a function that remembers its state across its calls
Charles C. Berry
cberry at tajo.ucsd.edu
Mon Feb 1 17:41:58 CET 2010
On Mon, 1 Feb 2010, Hao Cen wrote:
> 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.
>
Not quite true. See R-intro Section 10.7. Note the open.account example.
> g <- function(x=rep(NA,3)){ function(y) {x <<- c(x[2:3],y[1]);mean(x)}}
> f <- g()
> f(1)
[1] NA
> f(2)
[1] NA
> f(3)
[1] 2
> f(4)
[1] 3
> f(5)
[1] 4
>
HTH,
Chuck
> 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.
>
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901
More information about the R-help
mailing list