15.3 Using R6 as data storage
The idea is to storage the R functional framework inside an R6 class.
R6 is an encapsulated object-oriented programming (OOP) framework, a programming language used to construct the modular pieces of code that can be used to build blocks for large systems. It is used to structure a software program into simple, reusable pieces of code blueprints (classes) to create individual instances (objects). R is a functional programming language which uses R6 object-oriented programming-OOP.
- Sharing data across modules (field/class)
- Be sure it is tested (object)
(cac_5)
R6::R6Class(
MyData <-"MyData",
# Defining our public methods, that will be
# the dataset container, and a summary function
public = list(
data = NULL,
initialize = function(data){
$data <- data
self
}, summarize = function(){
summary(self$data)
}
) )
library(testthat, warn.conflicts = FALSE)
test_that("R6 Class works", {
# We define a new instance of this class, that will contain
# the mtcars data.frame
MyData$new(mtcars)
my_data <-# We will expect my_data to have two classes:
# "MyData" and "R6"
expect_is(my_data, "MyData")
expect_is(my_data, "R6")
# And the summarize method to return a table
expect_is(my_data$summarize(), "table")
# We would expect the data contained in the object
# to match the one taken as input to new()
expect_equal(my_data$data, mtcars)
# And the summarize method to be equal to the summary()
# on the input object
expect_equal(my_data$summarize(), summary(mtcars))
})
## Test passed 🎊