We can use any of the following methods to access the items of an array in R:
[]
c()
function.[]
We can access the items in an array by referring to their index positions, using the []
brackets.
array[row position, column position, matrix level]
# 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]
myarray
, with its elements or items starting from 1
and ending at 10
.3
by 2
dimensional array, using the array()
function.multiarray
for visual purposes.[1, 2]
.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:
,
) after the c()
function.,
) before the c()
function# 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]
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]
# 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]
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]
.