Data Structures – Matrix and Array in R

In the previous tutorial we saw atomic vectors and list. In this tutorial we look at Matrix and Array in R.


An array is a vector with additional attributes
which stores the dimension of the array and
which stores the names of the dimensions. Here’s an example:

This creates a 2,2,2 array. You can check if an object is an array by using the

The array has an attribute called dim.

You can also get the dimensions using the

we can assign names to the dimensions. In the example below we create a list with dimnames. The length of each element in the list should correspond to the dimension.


A matrix is an 2 dimensional array. Lets create one

The data is filled column first. nrow specifies number of rows and ncol specifies number of columns. To fill in rows first use the ‘byrow’ specifier

An element of a matrix can be accessed by specifying ‘row,column’

This retrieves the element at row 2 and column 3. You can also specify a single index

This accesses the elements in column first order. To select a complete row or complete column

Multiple rows or columns can also be accessed

You can assign names to the rows and columns. The names can be used to access the elements

You can check if an object is a matrix by using
. Length of a matrix is given by
. To find the number of rows and number of columns use the
functions respectively. To get all the dimensions use the

To get all the names of the rows use the
function and to get all the column names use the

We can combine two matrices row wise using
and columnwise using
. we Will explore this function in details in the subsequent tutorials, but for now, lets look at one example

We can convert the matrix back to a vector by using the c() function

A list can also be converted to a matrix.

So far we have been using cases where we provide all elements while creating a matrix. Lets look at two examples, where we provide less elements than is required by the ncol and nrow specification.

Leave a Reply

Your email address will not be published. Required fields are marked *