Menu
Coddy logo textTech

Checking With inherits()

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

inherits(x, "employee") asks whether employee is anywhere in the class vector of x, so it is TRUE for managers too. Comparing with class(x) == "employee" checks each position separately and gives a vector, which fails in an if:

m <- structure(list(), class = c("manager", "employee"))
print(inherits(m, "employee"))
print(inherits(m, "intern"))
print(class(m) == "employee")

Output:

[1] TRUE
[1] FALSE
[1] FALSE  TRUE

Given several names, inherits() is TRUE when the object has any of them. With which = TRUE it returns, for each name, its position in the class vector, or 0 when it is missing:

p <- structure(list(), class = c("fragile", "express", "parcel"))
print(inherits(p, c("letter", "parcel")))
print(inherits(p, c("express", "letter", "parcel"), which = TRUE))

Output:

[1] TRUE
[1] 2 0 3

A function that only makes sense for one family of classes checks its argument with inherits() and stops with a clear message otherwise:

raise <- function(x, pct) {
  if (!inherits(x, "employee")) stop("raise() needs an employee", call. = FALSE)
  x$salary <- x$salary * (1 + pct / 100)
  x
}
m <- structure(list(salary = 50000), class = c("manager", "employee"))
print(raise(m, 10)$salary)
print(tryCatch(raise(list(salary = 1), 10), error = function(e) conditionMessage(e)))

Output:

[1] 55000
[1] "raise() needs an employee"

Filter() with inherits() picks the members of one family from a mixed list, including every subclass:

staff <- list(
  structure(list(name = "Ada"), class = c("manager", "employee")),
  structure(list(name = "Bo"), class = "employee"),
  structure(list(name = "Cy"), class = c("intern", "employee")),
  structure(list(name = "Dee"), class = c("director", "manager", "employee"))
)
managers <- Filter(function(x) inherits(x, "manager"), staff)
print(vapply(managers, function(x) x$name, character(1)))

Output:

[1] "Ada" "Dee"
challenge icon

Challenge

Easy

A catalogue holds books, ebooks and DVDs. The constructors are given in Item.R, Book.R, Ebook.R and Dvd.R; an ebook has the class c("ebook", "book", "item"). In Catalogue.R complete two functions with inherits():

  • count_of(items, kind) returns how many items have kind anywhere in their class vector.
  • titles_of(items, kind) returns the titles of those items, in their order.

The supplied code reads lines book Dune, ebook Emma, dvd Alien and queries ? book, and prints book: 2 (Dune, Emma), or only dvd: 0 when nothing matches.

Your code goes in Item.R, Book.R, Ebook.R, Dvd.R and Catalogue.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("Item.R")
source("Book.R")
source("Ebook.R")
source("Dvd.R")
source("Catalogue.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
items <- list()
for (line in input) {
  p <- strsplit(line, " ")[[1]]
  rest <- paste(p[-1], collapse = " ")
  if (p[1] == "?") {
    titles <- titles_of(items, p[2])
    shown <- if (length(titles) > 0) paste0(" (", paste(titles, collapse = ", "), ")") else ""
    cat(p[2], ": ", count_of(items, p[2]), shown, "\n", sep = "")
  } else {
    items[[length(items) + 1]] <- switch(p[1], book = new_book(rest), ebook = new_ebook(rest), dvd = new_dvd(rest))
  }
}
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