Matrices

Matrices are R objects where elements are arranged in a two-dimensional rectangular layout.

Like arrays, they contain elements of the same data type.

Creating Matrices

A Matrix is created using the matrix() function. The matrix() function takes an atomic vector as input. We can also define how many rows should be in the matrix by setting the nrow argument to a number. Furthermore, we can also set the ncol argument, which tells R how many columns to include in the matrix.

Why Do We Need Matrices If We Have Arrays?

Matrices in R language are only 22 dimensional. A matrix is just a more convenient constructor. There are many functions and methods especially mathematical and statistical methods that only accept 2D arrays. So, to ensure that the programmer does not make the mistake of making the 2D array an nD array, a convenient object specifically for this task matrix is used.

Syntax

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

Here, data is the input vector, nrow is the number of rows to be created, ncol is the number of columns to be created, byrow is a logical clue: which if set to TRUE arranges elements row-wise and dimnames is the parameter that lets us assign names to the rows and columns.

Let’s have a look at the code to create an empty matrix:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy