How to Create a Matrix in R

The matrix() function can be used to create a matrix in R:

(1) Create a numeric matrix with 3 rows and 2 columns – filled by columns (default):

my_matrix <- matrix(data = c(12, 15, 18, 23, 25, 27), nrow = 3, ncol = 2)

print(my_matrix)

The result:

    [,1] [,2]
[1,]   12   23
[2,]   15   25
[3,]   18   27

(2) Create a numeric matrix with 3 rows and 2 columns – filled by rows (‘TRUE’):

my_matrix <- matrix(data = c(12, 15, 18, 23, 25, 27), nrow = 3, ncol = 2, byrow = TRUE)

print(my_matrix)

The result:

     [,1] [,2]
[1,]   12   15
[2,]   18   23
[3,]   25   27

(3) Create a categorial matrix with 3 rows and 2 columns – filled by columns (default):

my_matrix <- matrix(data = c("A", "B", "C", "D", "A", "C"), nrow = 3, ncol = 2)

print(my_matrix)

The result:

     [,1] [,2]
[1,] "A"  "D" 
[2,] "B"  "A" 
[3,] "C"  "C" 

(4) Create a categorial matrix with 3 rows and 2 columns – filled by rows (‘TRUE’):

my_matrix <- matrix(data = c("A", "B", "C", "D", "A", "C"), nrow = 3, ncol = 2, byrow = TRUE)

print(my_matrix)

The result:

   [,1] [,2]
[1,] "A"  "B" 
[2,] "C"  "D" 
[3,] "A"  "C"

Leave a Comment