R等价于Matlab的'持久'

时间:2011-12-16 21:53:04

标签: r matlab variables persistent

说我有一个matlab功能:

function y = myfunc(x)
    persistent a
    a = x*10
    ...

R声明persistent a中的等效声明是什么? <<-assign()

1 个答案:

答案 0 :(得分:4)

这是一种方式:

f <- local({ x<-NULL; function(y) {
   if (is.null(x)) { # or perhaps !missing(y)
      x <<- y+1
   }

   x
}})

f(3) # First time, x gets assigned
#[1] 4
f()  # Second time, old value is used
#[1] 4

local会在x<-NULL和函数声明周围创建一个新环境。因此,在函数内部,它可以转到x变量并使用<<-分配给它。

您可以找到这样的函数的环境:

e <- environment(f)
ls(e) # "x"
相关问题