R Classes and Objects
Classes and Objects
In R, everything you work with is an object: a number, a string, a vector, a list, a data frame, and even a function.
Every object has a class. The class tells R what kind of object it is, and how to work with it.
You have already used the class() function to find the class of an object:
Example
x <- 10
y <- "Hello"
z <- TRUE
class(x)
class(y)
class(z)
Try it Yourself »
What is a Class?
A class is like a template for objects, and an object is one thing made from that template.
For example, "Fruit" can be a class, and Apple, Banana and Mango are objects of that class. They are all fruits, but each one has its own name, color and taste.
| Class | Objects |
|---|---|
| Fruit | Apple, Banana, Mango |
| Car | Volvo, Audi, Toyota |
Why Classes Matter
Some R functions look at the class of an object, and do what fits that class.
For example, summary() shows statistics for numbers, but counts for a factor:
Example
numbers <- c(10, 20, 30, 40)
summary(numbers)
colors <- factor(c("red", "blue", "red"))
summary(colors)
Try it Yourself »
A function like summary() or print(), which works differently for each class, is called a generic function.
Create Your Own Classes
You can also create your own classes, for example a class for players in a game, with a name and points.
R has two main systems for this:
| System | Description |
|---|---|
| S3 | Simple and flexible. Most of R's own classes, like data frames and factors, use S3. |
| S4 | More formal and strict. You must describe the class first, and R checks the type of every value. |
You will learn both in the next chapters.