[R] static variable?

jim holtman jholtman at gmail.com
Thu Apr 16 15:08:05 CEST 2009


You can use 'local'

> counter()
> # create a function with a 'local static' variable
> counter <- local({
+     i <- 0
+     function() {
+         i <<- i + 1
+         i
+     }
+ })
>
> counter()
[1] 1
> counter()
[1] 2
> i <- 42  # change 'i' at this level
> counter()  # has not effect on the 'counter' i which is local
[1] 3
>


On Thu, Apr 16, 2009 at 8:46 AM, ivo welch <ivowel at gmail.com> wrote:
> dear R experts:
>
> does R have "static" variables that are local to functions?  I know
> that they are usually better avoided (although they are better than
> globals).
>
> However, I would like to have a function print how often it was
> invoked when it is invoked, or at least print its name only once to
> STDOUT when it is invoked many times.
>
> possible without <<- ?
>
> sincerely,
>
> /iaw
>
> ______________________________________________
> 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list