Arrays in R

Arrays in R can have more than two dimensions as compared to the matrix. Arrays in R, are created using the array() function. The array() function takes the vector as input and used its values in dim parameters to create an array. Suppose, we create an array of (2, 3, 4) dimensions, it will create 4 rectangular matrices of 2 columns and 2 rows.

Arrays in R
Arrays in R

Following is the syntax of arrays in R:

The following terms are used in array syntax:

data

The first argument in array() function is called the data. It is given to the array as an input function.

matrices

The array in R language consists of multi-dimensional matrices.

row_size

The number of row elements which an array can store are defined in this parameter.

column_size

The number of columns elements which an array can store are defined in this parameter.

dim_names

To change the default names of rows and columns this parameter is used.

To create an array we used array() function in R language, to specify the array dimensions dim parameter is used.

# An array from 1 to 20
arr <- c(1:20)
arr

# An array with more than one dimension
ma <- array(arr, dim = c(4, 3, 2))
ma

Output

1 30

Access Items of Arrays in R

The index position is used to access the elements of an array. To access the desired element from an array we used the [] brackets.

arr <- c(1:20)
ma <- array(arr, dim = c(5, 2, 2))

ma[2, 2, 2]

Output

ar2

To access the whole row or column from a matrix in an array, we used  the c() function:

arr <- c(1:20)

# Access all the items from row 1
ma <- array(arr, dim = c(5, 2, 2))
ma[c(1),,1]

# Access all the items from column 1
ma <- array(arr, dim = c(5, 2, 2))
ma[,c(1),1]

Output

ar3

A comma (,) before c() means that we want to access the column and a comma (,) after c() means that we want to access the row.

Check if an Item Exists

To check if a specified item is present in an array, we used the %in% operator. The following example is to check if the value “2” is present in the array:

arr <- c(1:20)
ma <- array(arr, dim = c(5, 2, 2))

2 %in% ma

Output

1 33

Amount of Rows and Columns

To find the amount of rows and columns in an array, the dim() function is used.

arr <- c(1:20)
ma <- array(arr, dim = c(5, 2, 2))

dim(ma)

Output

ar5

Array Length

To find the dimension of an array we used the length() function:

arr <- c(1:20)
ma <- array(arr, dim = c(5, 2, 2))

length(ma)

Output

ar6

Loop Through an Array

Using a for loop, you can loop through the array items.

arr <- c(1:20)
ma <- array(arr, dim = c(5, 2, 2))

for(x in ma){
  print(x)
}

Output

ar7