How to Create a Matrix in R?

To create a matrix in R you need to use the function called matrix. The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix and this is the important point you have to remember that by default, matrices are in column-wise order.

Example:

# R program to illustrate a matrix
 
A = matrix(
    # Taking sequence of elements
    c(1, 2, 3, 4, 5, 6, 7, 8, 9),
     
    # No of rows and columns
    nrow = 3, ncol = 3, 
 
    # By default matrices are
    # in column-wise order
    # So this parameter decides
    # how to arrange the matrix         
    byrow = TRUE                            
)
 
print(A)

Output:

   [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9