Object-Oriented Programming with S3 and R6 in R
Richie Cotton
Data Evangelist at DataCamp
initialize()
customizes startup
finalize()
customizes cleanup
thing_factory <- R6Class( "Thing", private = list( ..a_field = 123 ), public = list(
initialize = function(a_field) { if(!missing(a_field)) { private$a_field = a_field } },
finalize = function() { message("Finalizing the Thing") }
) )
a_thing <- thing_factory$new()
rm(a_thing)
gc()
Finalizing the Thing
used (Mb) gc trigger (Mb) max used (Mb)
Ncells 443079 23.7 750400 40.1 592000 31.7
Vcells 718499 5.5 1308461 10.0 1092342 8.4
library(RSQLite) database_manager_factory <- R6Class( "DatabaseManager", private = list(
conn = NULL
), public = list(
initialize = function(a_field) { private$conn <- dbConnect("some-database.sqlite") },
finalize = function() { dbDisconnect(private$conn) }
) )
finalize()
cleans up after R6 objectsObject-Oriented Programming with S3 and R6 in R