0
0
R-programmingHow-ToBeginner · 3 min read

How to Create Matrix in R: Syntax and Examples

In R, you create a matrix using the matrix() function by providing a vector of elements and specifying the number of rows and columns with nrow and ncol. The matrix fills by columns by default, but you can change this with byrow = TRUE.
📐

Syntax

The basic syntax to create a matrix in R is:

  • data: a vector of elements to fill the matrix.
  • nrow: number of rows in the matrix.
  • ncol: number of columns in the matrix.
  • byrow: logical value; if TRUE, fills the matrix by rows instead of columns.
r
matrix(data, nrow, ncol, byrow = FALSE)
💻

Example

This example creates a 3x3 matrix filled by rows using numbers 1 to 9.

r
m <- matrix(1:9, nrow = 3, ncol = 3, byrow = TRUE)
print(m)
Output
[,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9
⚠️

Common Pitfalls

Common mistakes include:

  • Not specifying nrow or ncol, which can cause unexpected matrix shapes.
  • Forgetting that by default, matrices fill by columns, which may confuse beginners.
  • Providing a data vector length that does not match nrow * ncol, which causes recycling of elements.
r
wrong_matrix <- matrix(1:4, nrow = 3, ncol = 3)
print(wrong_matrix)

correct_matrix <- matrix(1:9, nrow = 3, ncol = 3)
print(correct_matrix)
Output
[,1] [,2] [,3] [1,] 1 4 2 [2,] 2 1 3 [3,] 3 2 4 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9
📊

Quick Reference

ParameterDescriptionDefault
dataVector of elements to fill the matrixRequired
nrowNumber of rowsMust specify or ncol
ncolNumber of columnsMust specify or nrow
byrowFill matrix by rows if TRUEFALSE

Key Takeaways

Use the matrix() function with data, nrow, and ncol to create matrices in R.
By default, matrices fill by columns; use byrow = TRUE to fill by rows.
Ensure the length of data matches nrow * ncol to avoid recycling elements.
Always specify either nrow or ncol to define matrix dimensions clearly.
Check your matrix shape and content by printing it after creation.