Object-Oriented Programming with S3 and R6 in R
Richie Cotton
Data Evangelist at DataCamp
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)
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>
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" ...
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
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
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 } } )
)
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
new.env()
Object-Oriented Programming with S3 and R6 in R