R 中的静态变量
我在 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 编程语言做类似的事情吗?
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 )
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是使用闭包(在编程语言意义上)的一种方法,即将 count 变量存储在只能由您的函数访问的封闭环境中:
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:
这是另一种方法。 这个需要更少的打字并且(在我看来)更具可读性:
这个片段以及更复杂的概念示例可以通过找到 在这篇 R-Bloggers 文章中
Here is another approach. This one requires less typing and (in my opinion) more readable:
This snippet, as well as more complex example of the concept can by found in this R-Bloggers article
G. Grothendieck 似乎给出了正确的答案:在 R 函数中模拟静态变量< /a> 但不知怎的,这篇文章在谷歌搜索中获得了更有利的位置,所以我在这里复制这个答案:
在本地定义 f ,如下所示:
It seems the right answer was given by G. Grothendieck there: Emulating static variable within R functions But somehow this post got more favorable position in google search, so i copy this answer here:
Define f within a local like this: