Andy Barbour
Andy Barbour

Reputation: 8893

R equivalent of Matlab's 'persistent'

Say I have a matlab function:

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

What is the equivalent statement in R for the persistent a statement? <<- or assign()?

Upvotes: 2

Views: 855

Answers (1)

Tommy
Tommy

Reputation: 40841

Here's one way:

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

What happens is that local creates a new environment around the x<-NULL and the function declaration. So inside the function, it can get to the x variable and assign to it using <<-.

You can find the environment for a function like this:

e <- environment(f)
ls(e) # "x"

Upvotes: 4

Related Questions