Matrices
A matrix is a two-dimensional grid of values of a single type — rows and columns of numbers that R can index, summarise, and run linear-algebra operations on.
Learn Matrices in our free R course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free R course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
By the end of this lesson you'll create matrices with matrix(), index them by [row, col], name dimensions, and use built-in row/column summaries and matrix multiplication.
What You'll Learn in This Lesson
1️⃣ Building a Matrix
Pass a vector to matrix() with nrow and/or ncol . By default R fills column by column; use byrow = TRUE to fill across rows. dim() reports the shape.
2️⃣ Indexing by Row and Column
Index with m[row, col] . Leave a side blank to grab a whole row or column. Naming the dimensions with rownames() and colnames() lets you index by label.
3️⃣ Matrix Math
Element-wise math works just like vectors. R also gives you fast summaries — rowSums() , colMeans() — plus t() to transpose and %*% for genuine matrix multiplication.
Your turn. Fill in the # TODO blank, run it, and compare with the expected output.
Mini-Challenge: A Times-Table Grid
Write it from the outline, run it, and check it against the example output. outer() is a neat way to build a grid from two vectors.
Common Errors (and the fix)
- Matrix looks transposed — R filled by column. Add byrow = TRUE to fill in the order you typed values.
- "non-conformable arguments" — your matrices' dimensions don't line up for %*% . The first's columns must equal the second's rows.
- A row collapses to a vector — m[1, ] drops to a vector. Add drop = FALSE to keep it a matrix.
- Mixing types — putting text in a numeric matrix coerces everything to character. Matrices hold one type only; use a data frame for mixed columns.
Pro Tips
- 💡 Combine vectors fast: cbind() binds columns and rbind() binds rows into a matrix.
- 💡 Name dimensions: labelled rows/cols make indexing and output far easier to read.
- 💡 apply over a margin: apply(m, 1, max) gives the max of each row — preview of the apply lesson.
📋 Quick Reference — Matrices
Task
R Syntax
Create
matrix(1:6, nrow = 2)
Shape
dim(m)
Element / row / col
m[i, j] ; m[i, ] ; m[, j]
Row/col summary
rowSums(m) ; colMeans(m)
Transpose
t(m)
Matrix multiply
a %*% b
Frequently Asked Questions
🎉 Lesson Complete!
- ✅ A matrix is a 2-D grid of one type
- ✅ matrix(..., byrow = TRUE) controls fill order
- ✅ Index with m[row, col] ; blanks grab whole rows/cols
- ✅ rowSums() and colMeans() summarise fast
- ✅ %*% is true matrix multiplication
- ✅ Next lesson: Data Frames — the workhorse table for real data
Practice quiz
What kind of values can a single matrix hold?
- Values of one type only
- Any mix of types
- Only character strings
- Only whole numbers
Answer: Values of one type only. A matrix is a 2-D grid where every cell must be the same type.
What does byrow = TRUE do in matrix()?
- Sorts the rows
- Fills the matrix row by row
- Transposes the matrix
- Removes empty rows
Answer: Fills the matrix row by row. By default R fills by column; byrow = TRUE fills across rows in input order.
How does R fill a matrix by default?
- Randomly
- Row by row
- Diagonally
- Column by column
Answer: Column by column. Without byrow, R is column-major and fills down the first column first.
What does dim(m) return for a matrix?
- The total number of cells
- The rownames
- The number of rows and columns
- The largest value
Answer: The number of rows and columns. dim() reports the shape as c(rows, cols).
How do you select the whole first row of a matrix m?
Leaving the column index blank, m[1, ], grabs the entire first row.
Which operator does true matrix multiplication?
- *
- %*%
- %/%
- x()
Answer: %*%. %*% performs real matrix multiplication; plain * is element-wise.
What does rowSums(a) compute?
- The sum of all cells
- The product of each row
- The sum of each row
- The mean of each column
Answer: The sum of each row. rowSums() adds up the values in each row.
What does t(a) do to a matrix?
- Totals it
- Trims it
- Transposes rows and columns
- Truncates decimals
Answer: Transposes rows and columns. t() transposes the matrix, swapping its rows and columns.
Why might your matrix look 'transposed' from what you typed?
- R filled by column instead of by row
- matrix() reverses input
- dim() reordered it
- It used byrow = TRUE
Answer: R filled by column instead of by row. Default column-major fill surprises many beginners; add byrow = TRUE.
What causes a 'non-conformable arguments' error with %*%?
- Too many rows
- The dimensions don't line up for multiplication
- Using named dimensions
- A negative value
Answer: The dimensions don't line up for multiplication. For A %*% B, the first matrix's columns must equal the second's rows.
Continue this course
- Previous: Lists
- Next: Data Frames