Get startedGet started for free

Very Classy

Variables can have more than one class. In this case, class() (docs) returns a character vector of length greater than one.

Likewise you can set multiple classes by assigning a character vector to class(). The classes should be ordered from more specific to more general as you move left to right, since you want to begin with the behavior most targeted to your object. For example:

x <- c("a", "e", "i", "o", "u")
class(x) <- c("vowels", "letters", "character")

You can check for the other classes using the general purpose inherits() (docs) function. For example:

inherits(x, "vowels")

This exercise is part of the course

Object-Oriented Programming with S3 and R6 in R

View Course

Exercise instructions

The variable kitty has been predefined in your workspace.

  • View the kitty by typing its name.
  • Assign the classes "cat", "mammal", and "character" to the variable kitty.
  • Check that kitty has class "cat", and "mammal", "character" (one at a time, in that order) using inherits().
  • Check that kitty is still a character vector using is.character().
  • Check that kitty does not have class "dog".

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# View the kitty
kitty

# Assign classes
___ <- ___

# Does kitty inherit from cat/mammal/character?
inherits(___, "___")
___
___

# Is kitty a character vector?
___

# Does kitty inherit from dog?
___
Edit and Run Code