2011-12-16 70 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"