R Create Matrix

To create Matrix in R, call matrix() function, and pass the collection of items; number of rows and/or columns information as arguments in the function call.

In this tutorial, we will learn how to create a matrix from a collection of items using matrix() function.

Syntax

The syntax of matrix() function is

matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)

where

Argument Default Value Description
data NA A vector or a list.
nrow 1 Number of rows in the matrix.
ncol 1 Number of columns in the matrix.
byrow FALSE If FALSE, matrix is filled by columns. If TRUE, matrix is filled by rows.
dimnames NULL A list of length 2, with row and column names respectively.

Examples

In the following program, we create a matrix from a vector of length 6. The number of columns in the matrix is set to 3 using ncol argument.

example.R

data <- c(2, 4, 7, 5, 10, 1)
A <- matrix(data, ncol = 3)
print(A)

Output

[,1] [,2] [,3]
[1,]    2    7   10
[2,]    4    5    1

Please observe that the items from data are filled in the matrix by columns.

We may also specify number of rows using nrow argument, instead of number of columns to create a matrix.

Let us create a matrix from a vector, with 3 rows.

example.R

data <- c(2, 4, 7, 5, 10, 1)
A <- matrix(data, nrow = 3)
print(A)

Output

[,1] [,2]
[1,]    2    5
[2,]    4   10
[3,]    7    1

To fill the matrix by rows, pass TRUE for byrow argument.

example.R

data <- c(2, 4, 7, 5, 10, 1)
A <- matrix(data, nrow = 3, byrow = TRUE)
print(A)

Output

[,1] [,2]
[1,]    2    4
[2,]    7    5
[3,]   10    1

The elements in the matrix are filled by row.

Conclusion

In this R Tutorial, we learned how to create a Matrix in R using matrix() function, with the help of examples.