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

R Reference Methods

A reference class method is a function stored inside the class definition. A method reads and writes the fields of its own object through .self.

A method that adds one

bump adds one to count through .self. Two calls move the count from 0 to 2.

Counter <- suppressMessages(setRefClass("Counter", fields = list(count = "numeric"), methods = list(
  bump = function() {
    .self$count <- .self$count + 1
  }
)))
c1 <- Counter$new(count = 0)
c1$bump()
c1$bump()
print(c1$count)

A method with an argument

add takes an amount and adds it to count. The count climbs from 10 to 15 and then to 18.

Counter <- suppressMessages(setRefClass("Counter", fields = list(count = "numeric"), methods = list(
  add = function(amount) {
    .self$count <- .self$count + amount
  }
)))
c1 <- Counter$new(count = 10)
c1$add(5)
print(c1$count)
c1$add(3)
print(c1$count)

One method calls another

bump_twice calls bump twice through .self. One later bump call takes the count to 3.

Counter <- suppressMessages(setRefClass("Counter", fields = list(count = "numeric"), methods = list(
  bump = function() {
    .self$count <- .self$count + 1
  },
  bump_twice = function() {
    .self$bump()
    .self$bump()
  }
)))
c1 <- Counter$new(count = 0)
c1$bump_twice()
print(c1$count)
c1$bump()
print(c1$count)

A reset method

reset writes 0 into count through .self. The prints show the count fall back to 0 and climb again.

Counter <- suppressMessages(setRefClass("Counter", fields = list(count = "numeric"), methods = list(
  bump = function() {
    .self$count <- .self$count + 1
  },
  reset = function() {
    .self$count <- 0
  }
)))
c1 <- Counter$new(count = 8)
c1$bump()
print(c1$count)
c1$reset()
print(c1$count)
c1$bump()
print(c1$count)

Example

Counter <- suppressMessages(setRefClass("Counter", fields = list(count = "numeric"), methods = list(
  add = function(amount) {
    .self$count <- .self$count + amount
  },
  add_twice = function(amount) {
    .self$add(amount)
    .self$add(amount)
  }
)))
c1 <- Counter$new(count = 1)
c1$add(4)
print(c1$count)
c1$add_twice(10)
print(c1$count)
print(c1)

Key points

  • The methods value inside setRefClass() holds a list of named functions.
  • Each method runs through the object with $, as in c1$bump().
  • .self stands for the object the method is running on.
  • A method writes a field through .self, as in .self$count.
  • A method calls another method of the same object through .self as well.
  • Field changes made by a method stay with the object after the call ends.

In this example, add takes the count from 1 to 5. add_twice then calls add twice through .self and the count reaches 25, as the field dump confirms.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

Inside a method, what does .self$count refer to?