Menu
Coddy logo textTech

Lists With a Class

Part of the Object Oriented Programming section of Coddy's R journey. Lesson 2 of 57.

S3 is R's oldest and most used object system. An S3 object is an ordinary list with a class attribute, a label that says what kind of object it is. class(x) <- "dog" sets the label:

rex <- list(name = "Rex", age = 3)
class(rex) <- "dog"
print(class(rex))
cat(rex$name, "is", rex$age)

Output:

[1] "dog"
Rex is 3

structure() builds the value and sets its attributes in one call, which is the usual way to create an S3 object. The fields are read with $ as in any list:

rex <- structure(list(name = "Rex", age = 3), class = "dog")
print(class(rex))
print(is.list(rex))
print(rex$age)

Output:

[1] "dog"
[1] TRUE
[1] 3

The class is only a label: R does not check which fields an object has, so any list can be called a dog. unclass() removes the label and gives back the plain list:

p <- structure(list(x = 1, y = 2), class = "point")
print(unclass(p))

Output:

$x
[1] 1

$y
[1] 2

S3 objects are values. A function that changes an object changes its own copy, so it returns the new version and the caller assigns it. The original stays as it was:

birthday <- function(d) {
  d$age <- d$age + 1
  d
}
rex <- structure(list(name = "Rex", age = 3), class = "dog")
older <- birthday(rex)
cat(rex$age, older$age)

Output:

3 4
challenge icon

Challenge

Easy

Complete make_pet(name, species, age) in Pet.R. It returns a list with the fields name, species and age, in that order, and the class pet. Then complete describe_pet(p), which returns one sentence: a pet named Rex, species dog, age 3 gives Rex is a 3 year old dog.

The supplied code reads the name, species and age, creates the pet and prints its class, its field names and the sentence.

Your code goes in Pet.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("Pet.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
p <- make_pet(input[1], input[2], as.numeric(input[3]))
cat("class: ", class(p), "\n", sep = "")
cat("fields: ", paste(names(p), collapse = ", "), "\n", sep = "")
cat(describe_pet(p), "\n", sep = "")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online R compiler