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; ifTRUE, 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
nroworncol, 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
| Parameter | Description | Default |
|---|---|---|
| data | Vector of elements to fill the matrix | Required |
| nrow | Number of rows | Must specify or ncol |
| ncol | Number of columns | Must specify or nrow |
| byrow | Fill matrix by rows if TRUE | FALSE |
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.