Matrices in
R Programming
Learn to create, index, and manipulate matrices in R: the fundamental two-dimensional data structure for data science and statistics.
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.
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.
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.
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.
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.
byrow: Column vs. Row Fill
| 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:
Indexing: [row, col] Notation
Access any element using square bracket notation with the row index first, then the column index, separated by a comma.
Slicing Rows and Columns
Leave one index blank to extract an entire row or column. Combine with vectors for multiple selections.
Step-by-Step: Building a Matrix
Example 1: Student Grades
Create a matrix storing test scores for 3 students across 4 exams, then extract a specific score.
Example 2: Submatrix Extraction
Extract a submatrix containing only Alice and Carol's scores on Exams 2 and 3.
Example 3: Matrix Arithmetic
R supports element-wise operations and true matrix multiplication. Know the difference between * and %*%.
Common Mistakes
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?