[R] static variable?

Duncan Murdoch murdoch at stats.uwo.ca
Thu Apr 16 15:02:35 CEST 2009


On 4/16/2009 8:46 AM, ivo welch 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).

You put such things in the environment of the function.  If you don't 
want them to be globals, then you create the function with a special 
environment.  There are two common ways to do this:  a function that 
constructs your function (in which case all locals in the constructor 
act like static variables for the constructed function), or using 
local() to construct the function.

For example

 > makef <- function(x) {
+    count <- 0
+    function(y) {
+       count <<- count + 1
+       cat("Called ", count, "times\n")
+       y + x
+    }
+ }
 >
 > add3 <- makef(3)
 >
 > add3(4)
Called  1 times
[1] 7
 > add3(6)
Called  2 times
[1] 9

> 
> 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 <<- ?

That's exactly what <<- is designed for, so you'd have to use some 
equivalent with assign() to avoid it.

Duncan Murdoch




More information about the R-help mailing list