[R] persistant: Matlab->R
Greg Snow
Greg.Snow at intermountainmail.org
Thu Dec 14 22:12:34 CET 2006
It looks like the same process can be accomplished by using 'local' and
declaring the 'persistant' variables in a local scope, then the function
within that same scope, for example:
> inc <- local( { n <- 0; function(){n <<- n + 1; return(n)} } )
> inc
function(){n <<- n + 1; return(n)}
<environment: 0x09a8fee0>
> inc()
[1] 1
> inc()
[1] 2
> inc()
[1] 3
> inc()
[1] 4
Using local in R is a little more flexible in that you can have
variables that are shared between multiple functions, but not easily
accessable to the world at large:
> n <- 5
> incdec <- local( {n <- 0;
+ list(inc=function(){ n <<- n+1; return(n) },
+ dec=function(){ n <<- n-1; return(n) }
+ )})
> incdec$inc()
[1] 1
> incdec$inc()
[1] 2
> incdec$inc()
[1] 3
> incdec$dec()
[1] 2
> incdec$dec()
[1] 1
> incdec$inc()
[1] 2
> n
[5]
Hope this helps,
--
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at intermountainmail.org
(801) 408-8111
-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Bernard Gregory
Sent: Thursday, December 14, 2006 11:14 AM
To: r-help at stat.math.ethz.ch
Subject: [R] persistant: Matlab->R
Dear list members,
Could anyone tell me if there is an equivalent of the Matlab declaration
'persistant' in R?
Thank you very much,
Bernard Gregorry.
(Matlaber converted to R).
---------------------------------
[[alternative HTML version deleted]]
______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list