R matrices
last modified November 19, 2026
A matrix is a two-dimensional array: values arranged in rows and columns, all
of the same type. Matrices are used for tabular data, distance tables,
transition probabilities, and linear algebra. Internally a matrix is still a
vector, with a dim attribute that tells R how to arrange the
elements. This article shows how to create matrices, name their dimensions,
select rows and columns, combine them, multiply them, and solve a linear
system.
Creating a matrix
The function matrix takes a vector of values and a shape given by
nrow and ncol. By default the values fill the matrix
column by column: the first column is filled first, then the second,
and so on. The function dim returns the number of rows and columns
as a vector of length two.
m <- matrix(1:6, nrow = 2, ncol = 3)
print(m)
cat("dim:", dim(m), "\n")
The six values become a two-by-three matrix. The first column holds 1 and 2, the second holds 3 and 4, and the third holds 5 and 6. This column-major order is the default because R stores the matrix as one long vector and fills it down each column in turn.
$ Rscript building.R
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
dim: 2 3
Filling by row
The argument byrow = TRUE changes the filling order to row by row,
which is often the order in which a table is written on paper. The values are
the same, but their positions change, so the two matrices below are different
even though they contain the same six numbers.
m <- matrix(1:6, nrow = 2, byrow = TRUE) print(m)
The first row is now 1, 2, 3 and the second is 4, 5, 6. When the data already
comes in rows, byrow = TRUE avoids transposing the result
afterwards. When the data comes in columns, leave the default and save the
extra step.
$ Rscript byrow.R
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
Dimension names
The argument dimnames takes a list of two character vectors: the
row names first and the column names second. The functions
rownames and colnames read or set them separately.
Names make the printout self-explanatory and allow selection by label instead
of by position.
m <- matrix(c(90, 85, 78, 66), nrow = 2, byrow = TRUE,
dimnames = list(c("Ada", "Alan"), c("math", "art")))
print(m)
cat("rows:", rownames(m), "\n")
cat("cols:", colnames(m), "\n")
The matrix has two students as rows and two subjects as columns. The names are not values of the matrix; they are attributes that label the rows and columns. A matrix must still contain one type, so the names never appear as an extra column or an extra row.
$ Rscript dimension-names.R
math art
Ada 90 85
Alan 78 66
rows: Ada Alan
cols: math art
Indexing and dropping
A matrix is indexed with two subscripts inside one pair of brackets: the row
first, then the column. A blank subscript means every row or every column.
Selecting a single row or column returns a vector by default, because the
result has only one dimension; drop = FALSE keeps it as a matrix.
m <- matrix(1:6, nrow = 2, byrow = TRUE)
cat("element:", m[2, 3], "\n")
cat("row 1:", m[1, ], "\n")
cat("column 2:", m[, 2], "\n")
print(m[1, , drop = FALSE])
The element at row two and column three is 6. The first row is the vector 1, 2, 3, and the second column is the vector 2, 5. The last call keeps the one-by-three result as a matrix, which matters when the result is passed to a function that expects two dimensions.
$ Rscript indexing.R
element: 6
row 1: 1 2 3
column 2: 2 5
[,1] [,2] [,3]
[1,] 1 2 3
Combining matrices
rbind stacks matrices on top of each other, adding rows, and
cbind puts them side by side, adding columns. The two matrices
must agree on the dimension that is not being extended: rows for
cbind and columns for rbind.
a <- matrix(1:4, nrow = 2) b <- matrix(5:8, nrow = 2) print(rbind(a, b)) print(cbind(a, b))
The first result has four rows and two columns, and the second has two rows and
four columns. The values are arranged by column inside each source matrix, so
the columns of a and b keep their internal order.
Binding is how separate batches of measurements are assembled into one table.
$ Rscript binding.R
[,1] [,2]
[1,] 1 3
[2,] 2 4
[3,] 5 7
[4,] 6 8
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
Element-wise and matrix multiplication
The ordinary asterisk multiplies matrices element by element, which requires
them to have the same dimensions. The operator %*% performs
matrix multiplication: the entry in row i and column
j of the result is the sum of the products of row i of the
left matrix and column j of the right one.
a <- matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE) b <- matrix(c(5, 6, 7, 8), nrow = 2, byrow = TRUE) print(a * b) print(a %*% b)
The element-wise product multiplies 1 by 5, 2 by 6, and so on. The matrix product is different: 19 is 1 times 5 plus 2 times 7, and 22 is 1 times 6 plus 2 times 8. The inner dimensions must match, so a two-by-three matrix can be multiplied by a three-by-two matrix but not by another two-by-three one.
$ Rscript multiplying.R
[,1] [,2]
[1,] 5 12
[2,] 21 32
[,1] [,2]
[1,] 19 22
[2,] 43 50
Transpose and linear systems
t transposes a matrix, turning rows into columns and columns into
rows. det returns the determinant, a number that is zero exactly
when the matrix has no inverse. solve computes the inverse, or,
when given a vector as its second argument, solves the linear system
a %*% x = b directly.
a <- matrix(c(2, 1, -1, 3), nrow = 2, byrow = TRUE)
b <- c(5, 10)
x <- solve(a, b)
cat("det:", det(a), "\n")
print(t(a))
cat("x:", x, "\n")
cat("check:", a %*% x, "\n")
The system is 2x + y = 5 and -x + 3y = 10. Its
determinant is seven, so it has a unique solution, which is approximately
0.714 and 3.571. Multiplying the matrix by the solution returns the original
right-hand side, 5 and 10, which confirms the answer. Solving directly is more
accurate and faster than computing an inverse and multiplying it.
$ Rscript solving.R
det: 7
[,1] [,2]
[1,] 2 -1
[2,] 1 3
x: 0.7142857 3.571429
check: 5 10
Summaries by margin
apply calls a function for every row or every column of a matrix.
Its second argument is the margin: 1 means rows, 2 means columns, and
c(1, 2) means every single element. The function is applied to
each slice and the results are collected into a vector or a matrix.
m <- matrix(1:6, nrow = 2, byrow = TRUE)
cat("row sums:", apply(m, 1, sum), "\n")
cat("column means:", apply(m, 2, mean), "\n")
The row sums are 6 and 15, and the column means are 2.5, 3.5, and 4.5. The
result of apply keeps the dimension that was not consumed by the
margin, so a function over rows returns one value per row. The apply-family
article later in the series compares apply with
lapply and sapply.
$ Rscript margins.R row sums: 6 15 column means: 2.5 3.5 4.5
A complete example
The next script stores three students and two subjects in one matrix, then
computes each student's average with apply. The row names carry
the student names into the result, so the averages can be read without a
separate lookup table.
scores <- matrix(c(90, 85, 78, 66, 72, 95), nrow = 3, byrow = TRUE,
dimnames = list(c("Ada", "Grace", "Alan"),
c("math", "art")))
print(scores)
averages <- apply(scores, 1, mean)
cat("averages:", round(averages, 1), "\n")
Ada averages 87.5, Grace 72, and Alan 83.5. The result of apply
keeps the row names, which is why the printed vector is labelled. A matrix is
the right structure here because every student has the same two subjects; a
list of records would be the better choice if the subjects differed.
$ Rscript grades.R
math art
Ada 90 85
Grace 78 66
Alan 72 95
averages: 87.5 72 83.5
Next steps
The arrays article generalises the matrix to three or more dimensions, and the data frames article later in the series builds a table whose columns may have different types. The apply-family article covers the whole family of iteration functions, and the linear regression article uses matrix algebra to fit a model.
Source
An Introduction to R: arrays and matrices
The R Language Definition: indexing
R documentation: matrix multiplication
In this article we have built matrices in column and row order, named their
dimensions, and selected rows, columns, and single elements. We stacked and
joined matrices, compared element-wise multiplication with %*%,
transposed a matrix, solved a linear system, and summarised rows and columns
with apply. The series continues with
R arrays.
Author
List all R Language tutorials.