๐ŸŽ“ A1Learner
๐Ÿ”
0 of 27 lessons completed

R Reference Classes

A reference class defines objects that can change after they are built. setRefClass() writes the definition and $new() builds an object from it.

Build an object with $new

Counter is the name assigned to the definition. $new() builds one object and seeds count with 4.

Counter <- suppressMessages(setRefClass("Counter", fields = list(count = "numeric")))
c1 <- Counter$new(count = 4)
print(c1$count)

print shows the field dump

print() names the class and lists each field with its value. The dump holds no memory address.

Counter <- suppressMessages(setRefClass("Counter", fields = list(count = "numeric")))
c1 <- Counter$new(count = 7)
print(c1)

A class with two fields

Basket holds a numeric field and a character field. Each field reads back through $ and the full dump lists both.

Basket <- suppressMessages(setRefClass("Basket", fields = list(items = "numeric", label = "character")))
b <- Basket$new(items = 3, label = "fruit")
print(b$items)
print(b$label)
print(b)

A field can change

The count field is written through $ and reads back as 9. A second object keeps its own starting value of 1.

Counter <- suppressMessages(setRefClass("Counter", fields = list(count = "numeric")))
c1 <- Counter$new(count = 4)
c1$count <- 9
print(c1$count)
c2 <- Counter$new(count = 1)
print(c2$count)
print(c1$count)

Example

Counter <- suppressMessages(setRefClass("Counter", fields = list(count = "numeric")))
first <- Counter$new(count = 10)
second <- Counter$new(count = 20)
print(first$count)
print(second$count)
print(first)

Key points

  • setRefClass() takes the class name and a list of fields.
  • Each field entry pairs a field name with its class.
  • The definition sits inside suppressMessages() so a notice about a missing helper package does not print on systems where that notice appears.
  • The wrapped definition is assigned to a name, and that name works as the builder.
  • $new() builds an object and can seed a field with a starting value.
  • A field is read through the object name and $, as in c1$count.
  • print() shows a field dump with the class name and each field value.

In this example, two Counter objects start at 10 and 20. The print of the first object shows its field dump with the count of 10.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does Counter$new(count = 4) do?