Creating Matrices with matrix()
Build matrices by specifying data, nrow, ncol, and byrow.
Creating Matrices with matrix() is a free R Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, and your progress syncs across the web and the CoddyKit app. The R Academy course includes 4 lessons in total.
What is a Matrix in R?
A matrix in R is a two-dimensional data structure where all elements must be of the same type. Think of it as a table with rows and columns. Matrices are essential for linear algebra, image processing, and statistical computations.
# A simple 2x3 matrix
m <- matrix(1:6, nrow = 2, ncol = 3)
cat('A 2x3 matrix:
')
print(m)
cat('Dimensions:', dim(m), '
') # rows colsmatrix(data, nrow, ncol)
The matrix() function takes a vector of data and arranges it into rows and columns. By default, R fills the matrix column by column (column-major order).
# Filled column by column (default)
m_col <- matrix(1:12, nrow = 3, ncol = 4)
cat('Column-filled 3x4 matrix:
')
print(m_col)
cat('Note: 1,2,3 fill the first COLUMN, not the first row
')byrow = TRUE for Row-Filling
Setting byrow = TRUE fills the matrix row by row. This is often more intuitive when you are thinking of data in terms of rows (like a spreadsheet).
# Filled row by row
m_row <- matrix(1:12, nrow = 3, ncol = 4, byrow = TRUE)
cat('Row-filled 3x4 matrix:
')
print(m_row)
cat('Note: 1,2,3,4 fill the first ROW
')
# Verify byrow
m_check <- matrix(c(1,2,3,4,5,6), nrow = 2, byrow = TRUE)
print(m_check)Matrix from a Data Vector
You can create a meaningful matrix by passing a real data vector. R will recycle the vector if it is shorter than nrow * ncol, but it is best practice to provide exactly the right number of elements.
# Exam scores: 3 students, 4 subjects
scores_data <- c(88, 92, 75, 81, # Student 1
79, 85, 90, 73, # Student 2
95, 78, 82, 88) # Student 3
exam_matrix <- matrix(scores_data, nrow = 3, ncol = 4, byrow = TRUE)
rownames(exam_matrix) <- c('Alice', 'Bob', 'Carol')
colnames(exam_matrix) <- c('Math', 'Science', 'English', 'History')
print(exam_matrix)dim() — Checking Dimensions
dim(m) returns a numeric vector of length 2: the number of rows then the number of columns. You can also use nrow(m) and ncol(m) for individual dimensions.
m <- matrix(1:20, nrow = 4, ncol = 5)
cat('dim(m):', dim(m), '
') # 4 5
cat('nrow(m):', nrow(m), '
') # 4
cat('ncol(m):', ncol(m), '
') # 5
cat('Total elements:', length(m), '
') # 20is.matrix() — Type Checking
is.matrix(x) returns TRUE if x is a matrix. This is useful for validating function inputs. Note that a matrix is also an array (is.array() also returns TRUE).
m <- matrix(1:4, nrow = 2)
v <- c(1, 2, 3, 4)
cat('is.matrix(m):', is.matrix(m), '
') # TRUE
cat('is.matrix(v):', is.matrix(v), '
') # FALSE
cat('is.array(m): ', is.array(m), '
') # TRUE (matrix IS an array)
cat('class(m): ', class(m), '
')Zero Matrix and Identity Matrix
You can create special matrices by recycling a single value. matrix(0, n, n) creates a zero matrix; diag(n) creates an n x n identity matrix (1s on diagonal, 0s elsewhere).
# Zero matrix 3x3
zero_mat <- matrix(0, nrow = 3, ncol = 3)
cat('Zero matrix:
')
print(zero_mat)
# Identity matrix 3x3
identity_mat <- diag(3)
cat('Identity matrix:
')
print(identity_mat)Matrix from Recycled Values
When the data vector is shorter than nrow * ncol, R recycles the vector (repeats it from the beginning). R warns you if the vector length does not divide evenly into the matrix size.
# Recycle a 2-element vector into a 4x4 matrix
alternate <- matrix(c(0, 1), nrow = 4, ncol = 4)
cat('Recycled 0,1 into 4x4:
')
print(alternate)
# Checkerboard effect: fills column by columnProviding Only nrow or ncol
You only need to provide one of nrow or ncol — R calculates the other automatically based on the length of the data. If the data does not divide evenly, R will recycle and warn.
# Only specify nrow, R infers ncol
m1 <- matrix(1:12, nrow = 3)
cat('nrow=3 only, inferred ncol =', ncol(m1), '
')
print(m1)
# Only specify ncol, R infers nrow
m2 <- matrix(1:12, ncol = 4)
cat('ncol=4 only, inferred nrow =', nrow(m2), '
')Matrix of Characters
Matrices are not limited to numbers — you can create character matrices for categorical data, game boards, or lookup grids. However, all elements must still be of the same type.
# Tic-tac-toe board
board <- matrix(c('X', 'O', 'X',
'O', 'X', 'O',
'O', 'X', 'O'),
nrow = 3, ncol = 3, byrow = TRUE)
cat('Tic-Tac-Toe board:
')
print(board)
cat('Type:', class(board), '
')Creating Matrices: Summary
Here is a summary of ways to create matrices in R:
matrix(data, nrow, ncol)— basic creation (column-fill by default)matrix(data, nrow, ncol, byrow=TRUE)— fill row by rowmatrix(0, n, m)— zero matrixdiag(n)— identity matrixdim(m),nrow(m),ncol(m)— inspect dimensionsis.matrix(m)— type check
# Quick creation reference
cat('3x2 column-fill:
'); print(matrix(1:6, 3, 2))
cat('3x2 row-fill:
'); print(matrix(1:6, 3, 2, byrow=TRUE))
cat('2x2 zeros:
'); print(matrix(0, 2, 2))
cat('3x3 identity:
'); print(diag(3))Quick Check
By default (without byrow = TRUE), in what order does matrix() fill elements?
Recap: Creating Matrices
Excellent! Key takeaways from this lesson:
matrix(data, nrow, ncol)creates a matrix — data fills column by column by default- Use
byrow = TRUEto fill row by row - You only need to specify
nrowORncol— R infers the other dim(m)returnsc(rows, cols);nrow()andncol()give individual countsis.matrix()tests whether an object is a matrixmatrix(0, n, n)creates a zero matrix;diag(n)creates an identity matrix
# Full workflow: create, inspect, verify
m <- matrix(seq(2, 24, by = 2), nrow = 4, ncol = 3, byrow = TRUE)
cat('Even numbers matrix:
')
print(m)
cat('Rows:', nrow(m), '| Cols:', ncol(m), '| Elements:', length(m), '
')Learn R with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 43
- Lessons
- 159
Frequently Asked Questions
Is the “Creating Matrices with matrix()” lesson free?
Yes — any 3 lessons of the R Academy learning path, including “Creating Matrices with matrix()”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The R Academy course includes 4 lessons in total.
What will I learn in “Creating Matrices with matrix()”?
Build matrices by specifying data, nrow, ncol, and byrow. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start R Academy?
No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.
How long does the “Creating Matrices with matrix()” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this R Academy lesson?
Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Creating Matrices with matrix()
- Matrix Indexing and Subsetting
- Matrix Arithmetic and Operations
- Transposing and Reshaping Matrices