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")
Это упражнение является частью курса
Object-Oriented Programming with S3 and R6 in R
Инструкции к упражнению
The variable kitty has been predefined in your workspace.
- View the
kittyby typing its name. - Assign the classes
"cat","mammal", and"character"to the variablekitty. - Check that
kittyhas class"cat", and"mammal","character"(one at a time, in that order) usinginherits(). - Check that
kittyis still a character vector usingis.character(). - Check that
kittydoes not have class"dog".
Интерактивное практическое упражнение
Попробуйте выполнить это упражнение, дополнив этот пример кода.
# View the kitty
kitty
# Assign classes
___ <- ___
# Does kitty inherit from cat/mammal/character?
inherits(___, "___")
___
___
# Is kitty a character vector?
___
# Does kitty inherit from dog?
___