2

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()?

Andy Barbour
  • 8,783
  • 1
  • 24
  • 35

1 Answers1

4

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"
Tommy
  • 39,997
  • 12
  • 90
  • 85
  • That's nice, thanks. One question though... The matlab help reads "They differ from global variables in that persistent variables are known only to the function in which they are declared. This prevents persistent variables from being changed by other functions or from the MATLAB command line." Is your solution consistent with that statement? – Andy Barbour Dec 16 '11 at 22:54
  • @AndyBarbour Mostly it is. Unless you directly access it like Tommy did. Then you could change it like `e$x = 10`. – John Colby Dec 16 '11 at 22:59
  • @AndyBarbour - Well almost EVERYTHING in R can be changed if you put some effort into it ;-). Nobody can change the value by mistake though. So in that respect it is consistent with the MATLAB statement. – Tommy Dec 16 '11 at 23:06
  • I actually prefer the R flexibility here, though, since like you point out you still can't do it by mistake. – John Colby Dec 16 '11 at 23:38
  • Thank you all. Very insightful. – Andy Barbour Dec 17 '11 at 00:15
  • 1
    This function would be banned at `CRAN` because it modifies the global environment. Just be warned :-) – Carl Witthoft May 20 '15 at 13:49