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.

Array

An array is a vector with additional attributes
dim
which stores the dimension of the array and
dimnames
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
is.array()
function

The array has an attribute called dim.

You can also get the dimensions using the
dim
function

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.

Matrix

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
is.matrix()
. Length of a matrix is given by
length()
. To find the number of rows and number of columns use the
nrow()
and
ncol()
functions respectively. To get all the dimensions use the
dim()
function.

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

We can combine two matrices row wise using
rbind()
and columnwise using
cbind()
. 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.

This site uses Akismet to reduce spam. Learn how your comment data is processed.