Creating Matrices

The most direct way to create a new matrix is the matrix() function.

(m1 <- matrix(data = 1, nrow = 3, ncol = 3))
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    1

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
# Matrices must have at least a 'dim' attribute
attributes(m1)
$dim
[1] 3 3

The Matrix/Vector Relation

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.

# y1 is an ordinary numeric vector
class(y1)
[1] "numeric"
is.vector(y1)
[1] TRUE
is.matrix(y1)
[1] FALSE
# m1 is a matrix (which is a special case of an 'array')
class(m1)
[1] "matrix" "array" 
is.vector(m1)
[1] FALSE
is.matrix(m1)
[1] TRUE
# Add a 'dim' attribute to y1
attr(y1, "dim") <- c(3, 1)

# Now, y1 looks like a 3x1 matrix
y1
     [,1]
[1,]    1
[2,]    2
[3,]    3
# Indeed, y1 is now a matrix, as far as R is concerned
class(y1)
[1] "matrix" "array" 
attributes(y1)
$dim
[1] 3 1
is.vector(y1)
[1] FALSE
is.matrix(y1)
[1] TRUE

Similarly, we can convert a matrix to a vector by removing the dim attribute from the matrix.

# Setting the 'dim' attribute of m1 to NULL effectively removes that attribute
attr(m1, "dim") <- NULL

# Now, m1 looks like a vector
m1
[1] 1 1 1 1 1 1 1 1 1
# And R agrees: m1 is now a vector, not a matrix
class(m1)
[1] "numeric"
is.vector(m1)
[1] TRUE
is.matrix(m1)
[1] FALSE

Element Ordering

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.

matrix(1:9, 3, 3)
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

If we want to fill the matrix row-by-row instead (i.e., using row-major order), we can use the byrow = TRUE argument.

matrix(1:9, 3, 3, byrow = TRUE)
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
Back to top