Make it Classy (1)
As well as simply retrieving the class, the class()
function can be used to override it. The syntax is
class(x) <- "some_class"
This is particularly useful for lists, since lists can be used to combine other variables into more complex variables. (Remember the Lego analogy: individual variables are like Lego pieces, and you can use lists to build whatever you like.)
In this exercise, you'll look at an object to store the state of a chess game, and override its class.
To make sense of the exercise, you need to know a little bit about chess.
- There are two players in a chess game, named "white" and "black".
- Each player has six types of piece: a king, a queen, bishops, knights, rooks, and pawns.
- The position of each piece can be recorded using the row ("a" to "h") and the column (1 to 8).
This exercise is part of the course
Object-Oriented Programming with S3 and R6 in R
Exercise instructions
The list variable chess
has been predefined in your workspace.
- Explore
chess
to understand its structure. - Override the class of
chess
to be"chess_game"
. - Check whether or not
chess
is still a list, usingis.list()
(docs). - Determine the number of pieces still left on the board.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Explore the structure of chess
str(chess)
# Override the class of chess
___ <- ___
# Is chess still a list?
___
# How many pieces are left on the board?
___