R中的静态变量

时间:2009-07-06 18:48:46

标签: r closures static-variables

我在R中有一个多次调用的函数。我想跟踪我调用它的次数,并使用它来决定在函数内部做什么。这就是我现在所拥有的:

f = function( x ) {
   count <<- count + 1
   return( mean(x) )
}

count = 1
numbers = rnorm( n = 100, mean = 0, sd = 1 )
for ( x in seq(1,100) ) {
   mean = f( numbers )
   print( count )
}

我不喜欢我必须在函数范围之外声明变量count。在C或C ++中,我可以创建一个静态变量。我可以用R编程语言做类似的事吗?

3 个答案:

答案 0 :(得分:27)

这是使用闭包的一种方法(在编程语言意义上),即将count变量存储在只能由您的函数访问的封闭环境中:

make.f <- function() {
    count <- 0
    f <- function(x) {
        count <<- count + 1
        return( list(mean=mean(x), count=count) )
    }
    return( f )
}

f1 <- make.f()
result <- f1(1:10)
print(result$count, result$mean)
result <- f1(1:10)
print(result$count, result$mean)

f2 <- make.f()
result <- f2(1:10)
print(result$count, result$mean)
result <- f2(1:10)
print(result$count, result$mean)

答案 1 :(得分:5)

这是另一种方法。这个需要更少的打字和(在我看来)更具可读性:

f <- function(x) {
    y <- attr(f, "sum")
    if (is.null(y)) {
        y <- 0
    }
    y <- x + y
    attr(f, "sum") <<- y
    return(y)
}

此代码段以及更复杂的概念示例可以找到in this R-Bloggers article

答案 2 :(得分:0)

似乎 G. Grothendieck 给出了正确的答案:Emulating static variable within R functions 但不知何故这篇文章在谷歌搜索中获得了更有利的位置,所以我在这里复制了这个答案:

像这样在本地定义 f :

f <- local({ 
  static <- 0
  function() { static <<- static + 1; static }
})
f()
## [1] 1
f()
## [1] 2