I am looking for ways to emulate 'static' variables within R functions. (I know R is not a compiled language... hence the quotes.) With 'static' I mean that the 'static' variable should be persistent, associated to and modifiable from within the function.
My main idea is to use the attr
function:
# f.r
f <- function() {
# Initialize static variable.
if (is.null(attr(f, 'static'))) attr(f, 'static') <<- 0L
# Use and/or modify the static variable...
attr(f, 'static') <<- attr(f, 'static') + 1L
# return something...
NULL
}
This works well, as long as attr
can find f
. In some scenario's this is no longer the case. E.g.:
sys.source('f.r', envir = (e <- new.env()))
environment(e$f) <- .GlobalEnv
e$f() # Error in e$f() : object 'f' not found
Ideally I would use attr
on the 'pointer' of f
from within f
. sys.function()
and sys.call()
come to mind, but I do not know how to use these functions with attr
.
Anyone ideas or better design patterns on how to emulate 'static' variables within R functions?
Define f
within a local
like this:
f <- local({
static <- 0
function() { static <<- static + 1; static }
})
f()
## [1] 1
f()
## [1] 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With