<- matrix(data = 1, nrow = 3, ncol = 3)) (m1
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
[3,] 1 1 1
The most direct way to create a new matrix is the matrix()
function.
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.
# Create a numeric vector for comparison
y1 <- c(1, 2, 3)
# Basic vectors don't have attributes
attributes(y1)
NULL
$dim
[1] 3 3
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.
[1] "numeric"
[1] TRUE
[1] FALSE
[1] "matrix" "array"
[1] FALSE
[1] TRUE
[,1]
[1,] 1
[2,] 2
[3,] 3
[1] "matrix" "array"
$dim
[1] 3 1
[1] FALSE
[1] TRUE
Similarly, we can convert a matrix to a vector by removing the dim
attribute from the matrix.
By default, R fills matrices column-wise (i.e., using column-major order): the first column is filled top to bottom, then the second 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.