How to Create a Matrix in R

04.09.2021

Matrix are a fundemental data structure in mathematics. Most languages require a library to support matrices, but R has this feature built in. In this article, we will learn how to create a matrix in R.

There are a view ways to create a matrix in R. The first way is to start with all of our data in a vector, then use the matrix function to create a matrix from the vector. We also tell R how many rows and columns to use.

v = c(1, 2, 3, 4, 5, 6)

# 2 rows and 3 columns
matrix(v, 2, 3)
#>      [,1] [,2] [,3]
#> [1,]    1    3    5
#> [2,]    2    4    6

We can also create a matrix filled with the same value. Two common matrices are the 0 and NA matrices.

matrix(0, 2, 3)
#>      [,1] [,2] [,3]
#> [1,]    0    0    0
#> [2,]    0    0    0

matrix(NA, 2, 3)
#>      [,1] [,2] [,3]
#> [1,]   NA   NA   NA
#> [2,]   NA   NA   NA