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:
- We can simply refer to their index position or values, using brackets
[] - 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 variablemyarray <- c(1:10)# creating a multidimensional array using the array() functionmultiarray <- array(myarray, dim = c(3, 2))# printing the arraymultiarray# accessing the element in the first row and second columnmultiarray[1,2]
Code explanation
- Line 2: We create an array variable,
myarray, with its elements or items starting from1and ending at10. - Line 5: We create a
3by2dimensional array, using thearray()function. - Line 8: We print the array
multiarrayfor 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 thec()function. - To access the whole column in an array, we can add a comma (
,) before thec()function
Example 1: Accessing a row
# creating an array variablemyarray <- c(1:10)#creating a multidimensional array using the array() functionmultiarray <- array(myarray, dim = c(3, 2, 2))# printing the arraymultiarray# to access all the element in the first row from the first matrixmultiarray[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 variablemyarray <- c(1:10)#creating a multidimensional array using the array() functionmultiarray <- array(myarray, dim = c(3, 2, 2))# printing the arraymultiarray# to access all the element in the first row from the first matrixmultiarray[, 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].