01 / 20

Matrices in
R Programming

Learn to create, index, and manipulate matrices in R: the fundamental two-dimensional data structure for data science and statistics.

R Programming

What is a Matrix?

A matrix is a two-dimensional data structure in R that stores elements of the same type arranged in rows and columns. Think of it as a rectangular grid of values.

1 4 7 10 2 5 8 11 3 6 9 12 4 columns 3 rows

Why Matrices Matter in R

Matrices are the backbone of statistical computing and data analysis in R. Every dataset, image, and machine learning model relies on matrix operations under the hood.

Statistics
Correlation matrices, covariance matrices, and regression coefficients are all stored as matrices.
Data Storage
Spreadsheet-like data with rows of observations and columns of variables maps directly to a matrix.
Linear Algebra
Matrix multiplication, determinants, and inverses power everything from graphics to optimization.

Vectors vs. Matrices

A vector is one-dimensional (a single row or column). A matrix extends this to two dimensions. Both require elements of the same data type.

Vector 1 2 3 4 1D: length = 4 → Matrix 1 3 5 7 2 4 6 8 2D: 2 rows × 4 columns

The matrix() Function

The matrix() function is R's primary tool for creating matrices. It takes a data vector and reshapes it into the dimensions you specify.

matrix(data, nrow, ncol, byrow = FALSE)
data
The values to fill the matrix, provided as a vector.
nrow / ncol
Number of rows and columns. Specify at least one: R infers the other.
byrow
If TRUE, fills row-by-row. Default is FALSE (column-by-column).

Column-Major Fill Order

By default, R fills matrices column by column (column-major order). This is a critical detail that trips up many beginners.

m <- matrix(1:6, nrow = 2, ncol = 3)
1 2 3 4 5 6 Col 1 Col 2 Col 3 Fill order: 1 → 2 3 → 4 5 → 6 Down each column, then across to the next.

byrow: Column vs. Row Fill

# Column-major (default) matrix(1:6, nrow = 2) # Row-major matrix(1:6, nrow = 2, byrow = TRUE)
byrow = FALSE byrow = TRUE
Row 1 1, 3, 5 1, 2, 3
Row 2 2, 4, 6 4, 5, 6
Fill order Down columns Across rows

Understanding Dimensions

R provides three key functions to inspect a matrix's shape. For a \(3 \times 4\) matrix, these return:

m <- matrix(1:12, nrow = 3, ncol = 4) dim(m) # [1] 3 4 nrow(m) # [1] 3 ncol(m) # [1] 4 length(m) # [1] 12 (total elements)
dim()
Returns both dimensions as an integer vector: \( \texttt{c(nrow, ncol)} \).
nrow() / ncol()
Return individual dimensions. Useful for loops and conditionals.
length()
Returns the total number of elements: \( \text{nrow} \times \text{ncol} \).

Indexing: [row, col] Notation

Access any element using square bracket notation with the row index first, then the column index, separated by a comma.

r1 r2 r3 c1 c2 c3 1 4 7 2 5 8 3 6 9 m[2, 2] returns 5 matrix[row, column]

Slicing Rows and Columns

Leave one index blank to extract an entire row or column. Combine with vectors for multiple selections.

m <- matrix(1:12, nrow = 3) m[2, ] # Entire row 2: 2 5 8 11 m[ , 3] # Entire column 3: 7 8 9 m[1:2, 2:3] # Submatrix: rows 1-2, cols 2-3 m[-1, ] # All rows EXCEPT row 1
m[i, ]
Blank after the comma: select all columns for row i.
m[, j]
Blank before the comma: select all rows for column j.
m[-i, ]
Negative index: select all rows except row i.

Step-by-Step: Building a Matrix

1
Prepare your data vector. Use c() or the colon operator 1:n to create the values you want in the matrix.
2
Choose your dimensions. Decide how many rows and columns. Remember: \( \text{nrow} \times \text{ncol} \) must equal your vector length.
3
Set the fill order. Decide if you want column-major (default) or row-major (byrow = TRUE).
4
Verify with dim(). Always check the result. Use dim(), nrow(), and ncol() to confirm the shape.
5
Name your rows and columns. Optionally use rownames() and colnames() for readable output.

Example 1: Student Grades

Create a matrix storing test scores for 3 students across 4 exams, then extract a specific score.

scores <- c(85, 92, 78, 90, 88, 76, 95, 82, 89, 91, 84, 73) grades <- matrix(scores, nrow = 3, ncol = 4, byrow = TRUE) rownames(grades) <- c("Alice", "Bob", "Carol") colnames(grades) <- c("Exam1", "Exam2", "Exam3", "Exam4") grades[2, 3] # Bob's Exam 3 score: 95

Example 2: Submatrix Extraction

Extract a submatrix containing only Alice and Carol's scores on Exams 2 and 3.

# Using the grades matrix from Example 1 subset <- grades[c(1, 3), 2:3] subset # Exam2 Exam3 # Alice 92 78 # Carol 84 73 dim(subset) # [1] 2 2

Example 3: Matrix Arithmetic

R supports element-wise operations and true matrix multiplication. Know the difference between * and %*%.

A <- matrix(c(1, 2, 3, 4), nrow = 2) B <- matrix(c(5, 6, 7, 8), nrow = 2) A * B # Element-wise: each cell multiplied # [,1] [,2] # [1,] 5 21 # [2,] 12 32 A %*% B # True matrix multiplication # [,1] [,2] # [1,] 23 31 # [2,] 34 46

Common Mistakes

✕ Forgetting the comma
Writing \( \texttt{m[2]} \) returns the 2nd element in column-major order, not row 2. Use \( \texttt{m[2, ]} \) for row 2.
✕ Wrong fill order
Assuming byrow = TRUE by default. R fills column-first unless you explicitly set byrow.
✕ Mismatched lengths
If vector length doesn't divide evenly into the matrix, R recycles values silently with only a warning.
✕ Mixing * and %*%
Using \( \texttt{*} \) when you mean matrix multiplication. For linear algebra, always use \( \texttt{\%*\%} \).

Matrix Operations Cheat Sheet

Task R Code Result Type
Create matrix matrix(data, nrow, ncol) Matrix
Get dimensions dim(m) Integer vector
Single element m[i, j] Scalar
Entire row m[i, ] Vector
Entire column m[, j] Vector
Submatrix m[1:2, 2:3] Matrix
Transpose t(m) Matrix
Matrix multiply A %*% B Matrix

Question 1 of 5

What does matrix(1:6, nrow = 2) produce as the element in row 1, column 2?

Question 2 of 5

What does dim() return for a matrix with 4 rows and 5 columns?

Question 3 of 5

Given m <- matrix(1:9, nrow = 3), what does m[, 2] return?

Question 4 of 5

Which code creates a \(2 \times 3\) matrix filled row by row with values 10, 20, 30, 40, 50, 60?

Question 5 of 5

What is the key difference between * and %*% when used on two matrices in R?