12.2 Base versus OO objects

To tell the difference between a base and OO object, use is.object() or sloop::otype():

# A base object:
is.object(1:10)
#> [1] FALSE
sloop::otype(1:10)
#> [1] "base"

# An OO object
is.object(mtcars)
#> [1] TRUE
sloop::otype(mtcars)
#> [1] "S3"

Technically, the difference between base and OO objects is that OO objects have a “class” attribute:

attr(1:10, "class")
#> NULL

attr(mtcars, "class")
#> [1] "data.frame"

You may already be familiar with the class() function. This function is safe to apply to S3 and S4 objects, but it returns misleading results when applied to base objects. It’s safer to use sloop::s3_class(), which returns the implicit class that the S3 and S4 systems will use to pick methods. You’ll learn more about s3_class() in Section 13.7.1.

x <- matrix(1:4, nrow = 2)
class(x)
#> [1] "matrix" "array"
sloop::s3_class(x)
#> [1] "matrix"  "integer" "numeric"