(m1 <- matrix(data = 1, nrow = 3, ncol = 3)) [,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
[3,] 1 1 1
Creating matrices is procedural, but understanding why a matrix is “just a vector with a dim attribute” is conceptual, and that concept is the single most important idea on this page.
The most direct way to create a new matrix is the matrix() function. When we create a matrix, we need to provide some data for the matrix to hold, and we need to tell R how many rows and columns the matrix should contain.
If we inspect the object, we’ll see it now has an attribute, dim. The attribute dim is a two element vector, in which the first element shows the number of rows and the second element the number of columns.
Vectors, on the other hand, don’t have attributes.
# Create a numeric vector for comparison
y1 <- c(1, 2, 3)
# Basic vectors don't have attributes
attributes(y1)NULL
I’m not being facetious when I say that a matrix is just a vector with a dim attribute. In fact, we can convert a vector to a matrix simply by adding a dim attribute to the vector.
See: Notice that y1 is an ordinary numeric vector.
Unsurprisingly, y1 is not a matrix.
But we can change all that by adding a dim attribute to y1.
Now, y1 looks like a \(3 \times 1\) matrix when printed. Indeed, as far as R is concerned, y1 is now a matrix and no longer a vector.
Similarly, we can convert a matrix to a vector by removing the dim attribute from the matrix.
See: Notice that m1 is a matrix and not a vector.
As above, we’ll transmute m1 by manipulating its dim attribute. Specifically, we will remove the dim attribute entirely.
# Setting the 'dim' attribute of m1 to NULL effectively removes that attribute
attr(m1, "dim") <- NULL
m1[1] 1 1 1 1 1 1 1 1 1
Now, m1 prints like a length-nine vector, and R agrees: m1 is now a vector, not a matrix.
By default, R fills matrices column-wise (i.e., using column-major order): the first column is filled from top to bottom, then the second column is filled top to bottom, then the third column, and so on.
If we want to fill the matrix row-by-row instead (i.e., using row-major order), we can use the byrow = TRUE argument.
Predict what the matrix generated by matrix(1:6, nrow = 2, ncol = 3) will look like before running any code.
dim attribute, what do you get back?