Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emulating static variable within R functions

Tags:

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?

like image 783
Davor Josipovic Avatar asked Dec 01 '19 14:12

Davor Josipovic


1 Answers

Define f within a local like this:

f <- local({ 
  static <- 0
  function() { static <<- static + 1; static }
})
f()
## [1] 1
f()
## [1] 2
like image 115
G. Grothendieck Avatar answered Nov 15 '22 03:11

G. Grothendieck