How we can access array items in R

Overview

We can use any of the following methods to access the items of an array in R:

  1. We can simply refer to their index position or values, using brackets []
  2. We can make use of the c() function.

1. Accessing array items using brackets []

We can access the items in an array by referring to their index positions, using the [] brackets.

Syntax

array[row position, column position, matrix level]

Code example

# creating an array variable
myarray <- c(1:10)
# creating a multidimensional array using the array() function
multiarray <- array(myarray, dim = c(3, 2))
# printing the array
multiarray
# accessing the element in the first row and second column
multiarray[1,2]

Code explanation

  • Line 2: We create an array variable, myarray, with its elements or items starting from 1 and ending at 10.
  • Line 5: We create a 3 by 2 dimensional array, using the array() function.
  • Line 8: We print the array multiarray for visual purposes.
  • Line 11: We access the elements in the first row and second column of the array, by referring to their index positions in brackets [1, 2].

2. Accessing array items

We can also access the whole row or column from the matrix in an array by calling the c() function. There are two ways to access the items in a whole row or column:

  • To access the whole row in an array, we can add a comma (,) after the c() function.
  • To access the whole column in an array, we can add a comma (,) before the c() function

Example 1: Accessing a row

# creating an array variable
myarray <- c(1:10)
#creating a multidimensional array using the array() function
multiarray <- array(myarray, dim = c(3, 2, 2))
# printing the array
multiarray
# to access all the element in the first row from the first matrix
multiarray[c(1), , 1]

Code explanation

We are able to access the elements in the first row of the first matrix by using the c() function, such that we add a comma after the function. [c(1), , 1]

Example 2: Accessing a column

# creating an array variable
myarray <- c(1:10)
#creating a multidimensional array using the array() function
multiarray <- array(myarray, dim = c(3, 2, 2))
# printing the array
multiarray
# to access all the element in the first row from the first matrix
multiarray[, c(1), 1]

Code explanation

We are able to access the elements in the first column of the first matrix by using the c() function, such that we add a comma before the function [, c(1), 1].