![](https://static.isu.pub/fe/default-story-images/news.jpg?width=720&quality=85%2C50)
1 minute read
Building an R Package �������������������������������������������������������������������������������������������������
Chapter 10 ■ ObjeCt Oriented prOgramming
We can always assign a class to an object in this way, but changing the class of an existing object is considered bad style. We keep the data that belongs together in a list to make sure that the data is consistent, but the functionality we want to provide for a class is as much a part of the class as the data, so we also need to make sure that the functions that operate on objects of a given class always get data that is consistent with that class. We cannot do that if we go around changing the class of objects willy-nilly.
Advertisement
The function that creates the object should assign the class and then we should leave the class of the object alone. We can set the class with the class<- function and then return it using the blm function.
blm <- function(model, alpha = 1, beta = 1, ...) {
# stuff happens here...
object <- list(formula = model, frame = frame, mean = mean, covar = covar) class(object) <- "blm" object
The class is represented by an attribute of the object; however, and there is a function that sets these for us, called structure, and using that we can create the object and set the class at the same time, which is a little better.
blm <- function(model, alpha = 1, beta = 1, ...) {
# stuff happens here...
structure(list(formula = model, frame = frame, mean = mean, covar = covar), class = "blm")
Now that we gave the model object a class, let’s try printing it again.
model ## $formula ## y ~ x ## ## $frame ## y x ## 1 5.9784195 1.73343698 ## 2 0.5044947 -0.45442222 ## 3 -3.6050449 -1.47534377 ## 4 1.7420036 0.81883381 ## 5 -0.9105827 0.03838943 ## 6 -3.1266983 -1.14989951 ## 7 5.9018405 1.78225548 ## 8 2.2878459 1.29476972
260