🎓 A1Learner
🔍
0 of 27 lessons completed

R Copying and Sharing

Copying and sharing describe what happens when two names hold stored values. A plain value gives each name its own copy while a reference object gives both names the same object.

A copied list stands alone

box holds a count of 1 and copy starts as a copy of box. Writing 9 into the copy leaves the count in box at 1.

box <- list(count = 1)
copy <- box
copy$count <- 9
print(box$count)
print(copy$count)

Two names, one reference object

c2 is bound to the same object as c1. The bump call through c2 moves the count read through c1 from 2 to 3 as well.

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

A field write through the other name

The write sets the count field through c2. Reading the field through c1 gives 10, because both names reach the same object.

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

An environment box shares too

alias is bound to the same environment as box. Writing 9 through alias changes the value read through box.

box <- new.env()
box$count <- 2
alias <- box
alias$count <- 9
print(box$count)
print(alias$count)

Example

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

Key points

  • A plain list is copied when it is assigned to a new name.
  • A change to the copy leaves the original list alone.
  • Two names bound to one reference object share that object.
  • A change made through one name shows through the other name.
  • An environment box shares in the same way as a reference object.
  • A second call to $new() builds a separate object with its own fields.

In this example, shared is bound to the same counter as first, so two bump calls move the count read through first to 3. A fresh counter built with $new() still holds its own count of 1.

Note

Sharing comes from holding the same object, not from the name used to reach it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · rdrr.io R Snippets

Exercise

Two names share one reference object and a method call through the second name adds one to its count field. What does reading the count through the first name show?