R Language Object-Oriented Programming in R S3

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The S3 object system is a very simple OO system in R.

Every object has an S3 class. It can be get (got?) with the function class.

> class(3)
[1] "numeric"

It can also be set with the function class:

> bicycle <- 2
> class(bicycle) <- 'vehicle'
> class(bicycle)
[1] "vehicle"

It can also be set with the function attr:

> velocipede <- 2
> attr(velocipede, 'class') <- 'vehicle'
> class(velocipede)
[1] "vehicle"

An object can have many classes:

> class(x = bicycle) <- c('human-powered vehicle', class(x = bicycle))
> class(x = bicycle)
[1] "human-powered vehicle" "vehicle" 

When using a generic function, R uses the first element of the class that has an available generic.

For example:

> summary.vehicle <- function(object, ...) {
+   message('this is a vehicle')
+ }
> summary(object = my_bike)
this is a vehicle

But if we now define a summary.bicycle:

> summary.bicycle <- function(object, ...) {
+   message('this is a bicycle')
+ }
> summary(object = my_bike)
this is a bicycle


Got any R Language Question?