Search code examples
roopr6

In object-oriented R programming, what is an "active binding"?


In object-oriented R programming (especially Winston Chang's R6 package), what is an active binding?


Solution

  • First it is probably best to understand what a "binding" is. If we run code like:

    x <- 5
    

    then what has happened inside the computer is that we have put the value of 5 into a slot of memory and we have also 'bound' the name "x" to that location and value so that later we can use x and it will go to that memory location and look up the value (which is 5 until we change it to something else). This is called a static binding because the value does not change unless the program specifically makes a change.

    An active binding is similar in that we bind a variable name (like "x") to something, but that something is not just a constant value, but rather a function that will be run every time we try to access x. So you could bind the name "x" to a function that calls rnorm and then each time you access x you would see a different random normal value.

    Another example, consider if we do something with static bindings like:

    mydf <- data.frame( x=1:10, y=10:1 )
    df.size <- nrow(mydf)
    mydf <- data.frame(z=1:100)
    

    Now the variable df.size has the number of rows of mydf when it was created, not how many rows it has now (since nrow was run once, then the result was put into the df.size variable as a static binding, it does not update with changes to the data frame). If on the other hand we created an active binding between df.size and a function that ran nrow(mydf) then any time we looked at the "value" of df.size then it would show the current number of rows in mydf no matter how many times we change it.