R中的静态变量 [英] Static Variables in R

查看:117
本文介绍了R中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a function in R that I call multiple times. I want to keep track of the number of times that I've called it and use that to make decisions on what to do inside of the function. Here's what I have right now:

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 )
}

我不喜欢,我必须声明的变量计数超出了函数的范围。在C或C ++我可以只做一个静态变量。我可以在R编程语言中做类似的事吗?

I don't like that I have to declare the variable count outside the scope of the function. In C or C++ I could just make a static variable. Can I do a similar thing in the R programming language?

推荐答案

这里有一种方法使用闭包),即将计数变量存储在只能由您的函数访问的封闭环境中:

Here's one way by using a closure (in the programming language sense), i.e. store the count variable in an enclosing environment accessible only by your function:

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)

这篇关于R中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆