I was curious if there was a way to create class variables for R6 classes within the definition of the class? I read through the Introduction to R6 classes vignette but didn't find any mention of class variables. I am able to create class variables after creating the class using ClassName$variableName <- initial_value
but was curious if there was a way to do this within the actual class definition.
As an example, consider the Person
class below, which has a class variable count
which keeps track of the number of Person
objects that have been instantiated:
library(R6)
Person <- R6Class("Person",
public = list(
name = NA,
initialize = function(name) {
Person$count <- Person$count + 1
if (!missing(name)) self$name <- name
}
)
)
Person$count <- 0
Person$count # 0
john <- Person$new("John")
Person$count # 1
james <- Person$new("James")
Person$count # 2