A cleaner method would be to use an object-oriented approach. There is already an answer using reference classes.
A typical object-oriented approach with classes would create a class and then create a singleton object, i.e. one object of this class. Of course, it's a little wasteful to create a class just to create one object from it, so here we give an example of proto. (Creating a function to enable count , and a function that does the real work, has a similar problem - you create a closing function only to run it once.) The proton model allows you to create an object directly bypassing the need to create a class to use it once. Here foobar is a proto-object with the count property and stats , statfoo and statbar . Note that we excluded stats to avoid duplicating its code in each of statfoo and statbar . (continued further)
library(proto) foobar <- proto(count = 0, stats = function(., x) { .$count <- .$count + 1 list(mean = mean(x), count = .$count) }, statfoo = function(., x) c(.$stats(x), plus = 2), statbar = function(., x) c(.$stats(x), plus = 3) ) foobar$statfoo(1:3) foobar$statbar(2:4)
giving:
> foobar$statfoo(1:3) $mean [1] 2 $count [1] 1 $plus [1] 2 > foobar$statbar(2:4) $mean [1] 3 $count [1] 2 $plus [1] 3
The second construct would be to have statfoo and statbar as independent functions and store count and stats in foobar (continued further)
library(proto) foobar <- proto(count = 0, stats = function(., x) { .$count <- .$count + 1 list(mean = mean(x), count = .$count) } ) statfoo <- function(x) c(foobar$stats(x), plus = 2) statbar <- function(x) c(foobar$stats(x), plus = 3) statfoo(1:3) statbar(2:4)
gives a similar conclusion in the previous example.
The third approach . Of course, the second variation can be easily implemented using local and a function that brings us closer to where you started. This does not use any packages, but does not create a function just to remove it:
foobar <- local({ count <- 0 function(x) { count <<- count + 1 list(mean = mean(x), count = count) } }) statfoo <- function(x) c(foobar(x), plus = 2) statbar <- function(x) c(foobar(x), plus = 3) statfoo(1:3) statbar(2:4)