Classes created when restructuring a vector

Just a small detail and I don't know whether it is of relevance or not. Following the "Hands-on programming with R" book in the chapter about Classes I entered the following code (## indicates console output):

die = 1:6
class(die)

"integer"

dim(die) <- c(2, 3)
class(die)

"matrix" "array"

According to the book the class of die in the end should be "matrix" only. For some reason my R turned the first row into a matrix and the second row into an array. Does anyone know the reason for that and how this can be resolved?

Is the book written prior to R version 4 release ?
A matrix is the special case of a two-dimensional array. Since R 4.0.0, inherits(m, "array") is true for a matrix m.

Okay, but what's the point of classifying the first row as a matrix and the second as an array?

This is not what has occurred. The object has two classes. There is no row wise relationship as you suppose.

But when I type "die[class(die)=="array"]" it prints:
[1] 2 4 6
and when I type "die[class(die)=="matrix"]" it prints:
[1] 1 3 5

But that might be some invalid syntaxing with this kind of data type.

this evaluates to FALSE TRUE ,because matrix the first class is not array and array the second class is array.
vice versa for testing if class(die)=="matrix")

In other words, its a coincidence, matrix is the first class entry, array is the 2nd. you are indexing into the array/matrix with these numbers, and get parts of the array/matrix that correspond to those numbers, but this does not signify membership of parts of the array/matrix to the respective classes.

Going a little deeper, this is a good example of it being problematic practice to use the string based results of class(x) to understand whether an object is or isnt a class member. Often its way better in your programming to use an is.y(x) style function to answer that for you in a binary way.

is.array(die)
is.matrix(die)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.