2011-12-16 94 views
2

说我有一个matlab功能:[R相当于Matlab的“老大难”

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

什么是R等价声明为persistent a声明? <<-assign()

+1

答案取决于什么执着在MATLAB究竟。 – 2011-12-16 21:56:59

+1

http://stackoverflow.com/questions/7262485/options-for-caching-memoization-hashing-in-r – 2011-12-16 22:03:55

回答

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"