Emulating C-like static variables in R

Haroun Shihab
2 min readJan 31, 2016

--

If you want to count how many times a specific function has been called in the C (or C++) programming language, then you’d use a static variable.

For example:

void some_function() {
static int count = 0;
count ++;
printf(“%d\n”, count); // outputs the value of count
}
int main() {
some_function(); // prints 1
some_function(); // prints 2
some_function(); // prints 3
some_function(); // prints 4
some_function(); // prints 5
return 0;
}

Say you are in a situation where you want to do this in R. Does R have this notion of “static” variables ? Well, No … but we can easily mimic it using two approaches.

The attr function

R’s attr function let’s you assign attributes to objects. Let’s look at an example:

some_function <- function() {  //get the value of the attribute "running_count"
count <- attr(some_function, "running_count")

//initially there's no attribute called "running_count" so our
//count variable would be null
if(is.null(count)) {
//initialize our pseudo static variable
count <- 0
}
//update the value of count
count <- count + 1
//set the updated value using attr
attr(some_function, "running_count") <<- count
print(count)}

Now let’s see if this actually works

> some_function()
[1] 1
> some_function()
[1] 2
> some_function()
[1] 3
> some_function()
[1] 4

Voila! It works

But one might ask, why is there double arrows on this line ?

attr(some_function, "running_count") <<- count

We need to use this operator to tell R to store the “running_count” attribute globally, because if you we use the normal assignment operator `<-` R would set the attribute locally (i.e in the function’s scope only).

Check out this stack overflow post for more about the double assignment operator

Now onto the second method ..

Closures

In other words, set up an enclosing environment for our count variable accessible only by your function

make.some_function <- function() {
count <- 0
f <- function() {
count <<- count + 1
print(count)
}
return(f)
}

Let’s test this!

> some_function <- make.some_function()
> some_function()
> [1] 1
> some_function()
> [1] 2
> some_function()
> [1] 3

This works too!

Now you are armed with two ways to emulate C-like static variables in R.

--

--