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