class, typeof

Determine the class of an object or its "internal" type. The former will be useful to most R users while the latter only to a smaller subset. Note that the class function is much more powerful than it first appears. You can use it to create new S3 classes in R. (This post isn’t complete on this topic, but I’ll provide more information in the coming weeks.)
  • x – Any R object.
  • x – Any R object.

Example. Below a linear model is created. We examine the class of each object. Ultimately, a linear model is just a list with a class of "lm". Below we update the linear model g to be an object of class "myLM". We also create a print method for this new S3 class. (This is no mistake: that’s how easy it is to make a new class in R!)
> set.seed(2)
> x <- 1:10
> class(x)
[1] "integer"
> typeof(x)
[1] "integer"
> y <- x/5 + rnorm(10)
> class(y)
[1] "numeric"
> typeof(y)
[1] "double"
> g <- lm(y ~ x)
> class(g)
[1] "lm"
> typeof(g)
[1] "list"
> class(g) <- "myLM"
> print.myLM <- function(x){
+ 	print(x$coefficients)
+ }
> g
(Intercept)           x 
 -0.3225306   0.2970331 
The print method for the class "myLM", created above, just prints the coefficients of the model. However, the object g retains all of the original linear model information even in this new class.
Tip. When creating a custom function that outputs a specific type of object, it may be useful to make a new class to represent output from that function. Such a class is called an S3 class, and you can construct S3 methods for a new class quite easily. For instance, if myClass is the name a new S3 class that I just created, then I can make it print a certain way by writing a function called print.myClass. Similarly, I could customize what summary outputs by creating a summary.myClass function, and so on.

Leave a Reply