Environments, Reference Behavior, & Shared Fields

Object-Oriented Programming with S3 and R6 in R

Richie Cotton

Data Evangelist at DataCamp

 

 

 

           list

Object-Oriented Programming with S3 and R6 in R

 

 

 

           list

 

 

           environment

Object-Oriented Programming with S3 and R6 in R

 

env <- new.env()
lst <- list(x = pi ^ (1:5), y = matrix(month.abb, 3))
env$x <- pi ^ (1:5)
env[["y"]] <- matrix(month.abb, 3)
Object-Oriented Programming with S3 and R6 in R

 

lst
$x
3.141593   9.869604  31.006277  97.409091 306.019685

$y
     [,1]  [,2]  [,3]  [,4] 
[1,] "Jan" "Apr" "Jul" "Oct"
[2,] "Feb" "May" "Aug" "Nov"
[3,] "Mar" "Jun" "Sep" "Dec"
env
<environment: 0x103f3dfc8>
Object-Oriented Programming with S3 and R6 in R

 

ls.str(lst)
x :  num [1:5] 3.14 9.87 31.01 97.41 306.02
y :  chr [1:3, 1:4] "Jan" "Feb" "Mar" "Apr" "May" ...
ls.str(env)
x :  num [1:5] 3.14 9.87 31.01 97.41 306.02
y :  chr [1:3, 1:4] "Jan" "Feb" "Mar" "Apr" "May" ...
Object-Oriented Programming with S3 and R6 in R

 

lst2 <- lst
(lst$x <- exp(1:5))
2.718282   7.389056  20.085537  54.598150 148.413159
lst2$x
3.141593   9.869604  31.006277  97.409091 306.019685
identical(lst$x, lst2$x)
FALSE
Object-Oriented Programming with S3 and R6 in R

 

env2 <- env
(env$x <- exp(1:5))
2.718282   7.389056  20.085537  54.598150 148.413159
env2$x
2.718282   7.389056  20.085537  54.598150 148.413159
identical(env$x, env2$x)
TRUE
Object-Oriented Programming with S3 and R6 in R

 

 

 

               copy by value

Object-Oriented Programming with S3 and R6 in R

 

 

 

               copy by value

 

           copy by reference

Object-Oriented Programming with S3 and R6 in R
thing_factory <- R6Class(
  "Thing",
  private = list(

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

 

a_thing <- thing_factory$new()
another_thing <- thing_factory$new()
a_thing$a_shared_field
123
another_thing$a_shared_field
123
a_thing$a_shared_field <- 456
another_thing$a_shared_field
456
Object-Oriented Programming with S3 and R6 in R

Summary

  • Create environments with new.env()
  • Manipulate them using list syntax
  • Environments copy by reference
  • Share R6 fields using an environment field
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...