Cloning R6 Objects

Object-Oriented Programming with S3 and R6 in R

Richie Cotton

Data Evangelist at DataCamp

 

 

  • Environments use copy by reference
  • So do R6 objects
Object-Oriented Programming with S3 and R6 in R

 

thing_factory <- R6Class(
  "Thing",

private = list( ..a_field = 123 ),
active = list( a_field = function(value) { if(missing(value)) { private$..a_field } else { private$..a_field <- value } } )
)
Object-Oriented Programming with S3 and R6 in R

 

a_thing <- thing_factory$new()
a_copy <- a_thing

a_thing$a_field <- 456
a_copy$a_field
456
Object-Oriented Programming with S3 and R6 in R

 

 

 

clone() copies by value

Object-Oriented Programming with S3 and R6 in R

 

a_clone <- a_thing$clone()
a_thing$a_field <- 789
a_clone$a_field
456
Object-Oriented Programming with S3 and R6 in R

 

container_factory <- R6Class(
  "Container",

private = list( ..thing = thing_factory$new() ),
active = list( thing = function(value) { if(missing(value)) { private$..thing } else { private$..thing <- value } } )
)
Object-Oriented Programming with S3 and R6 in R

 

a_container <- container_factory$new()
a_clone <- a_container$clone()
a_container$thing$a_field <- "a new value" 
a_clone$thing$a_field
"a new value"
Object-Oriented Programming with S3 and R6 in R

 

a_deep_clone <- a_container$clone(deep = TRUE)
a_container$thing$a_field <- "a different value" 
a_deep_clone$thing$a_field
"a new value"
Object-Oriented Programming with S3 and R6 in R

Summary

  • R6 objects copy by reference
  • Copy them by value using clone()
  • clone() is autogenerated
  • clone(deep = TRUE) is for R6 fields
Object-Oriented Programming with S3 and R6 in R

Let's practice!

Object-Oriented Programming with S3 and R6 in R

Preparing Video For Download...