What is the matrix() function in R?

Overview

A matrix is simply a set of numbers arranged in rows and columns to form a rectangular array. The numbers inside a matrix are called the elements, or entries, of the matrix.

The matrix() function in R is used to create a matrix.

In this shot, we’ll learn how to use the matrix() function to create matrices in R.

Syntax

matrix(data, nrow, ncol, byrow, dimnames)

Parameter values and descriptions

Parameter



Description

data

The input vector that becomes the data elements of the matrix; required.

nrow

The desired number of rows; required.

ncol

Tthe most desired number of columns.

byrow

An optional, logical value that is ``FALSE`` by default and so the matrix is filled by columns. If otherwise, the matrix is filled by rows.

dimnames

An optional attribute for the matrix of length two(``2``) that gives the respective names of the rows and columns of the matrix.

Example 1

Let us create a matrix and use the matrix() function.

# using the matrix() function to create a matrix
mymatrix <- matrix(
c(1,2,3,4,5,6), #data
nrow = 2, # number of rows
ncol = 2, # number of columns
byrow = FALSE, # matrix filling
dimname = list(
c("row1", "row2"),
c("Col1", "Col2")
) # names of rows and columns
)
# printing the matrix
mymatrix

Explanation

In the program above, we create a matrix, mymatrix, in which we use the matrix() function and its various parameter values to make the mymatrix become a 2 × 2 matrix (i.e. 2 rows and 2 columns matrix) and also with their dimension names (row1, row2, col1, col2).

Note that the c() function is used to concatenate items together.

Example 2

In this example, we create a matrix with strings.

#using the matrix() function to create a matrix of strings
mymatrix <- matrix(
c(
"America", "China", "Jamaica",
"Turkey", "Sweeden", "Brazil"), # data
nrow = 3, # number of rows
ncol = 2 #number of columns
)
# printing the matrix
mymatrix

Explanation

In this shot, we’eve created a matrix, mymatrix, that has string elements, and use the various parameter values to make the matrix a 3 × 2 matrix.