[R] how to write a function that remembers its state across its calls
Hao Cen
hcen at andrew.cmu.edu
Mon Feb 1 17:25:32 CET 2010
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
More information about the R-help
mailing list