Unlocking the Power of Arrays in R
What is an Array?
An array is a powerful data structure that can store data of the same type in multiple dimensions. While vectors and matrices are limited to one and two dimensions, respectively, arrays can have three or more dimensions. To fully understand arrays, it’s essential to have a solid grasp of R vectors and matrices.
Creating an Array in R
To create an array in R, you can use the array()
function. The syntax is straightforward: array(vector, dim)
. Here, vector
represents the data items of the same type, and dim
specifies the dimensions of the array.
Let’s create an array named array1
with two 2×3 matrices:
array1 <- array(c(1:12), dim = c(2,3,2))
The output will be two 2×3 matrices with values from 1 to 12.
Accessing Array Elements
To access specific elements of an array, you can use the vector index operator [ ]
. The syntax is: [n1, n2, mat_level]
, where n1
specifies the row position, n2
specifies the column position, and mat_level
specifies the matrix level.
For example, to access the element at the 1st row, 3rd column of the 2nd matrix, you can use:
array1[1, 3, 2]
This will return the value 11.
Accessing Entire Rows or Columns
You can also access entire rows or columns by passing the desired value inside [ ]
. For example:
array1[, 2, 1] # access 2nd column elements of 1st matrix
array1[1,, 2] # access 1st row of 2nd matrix
Checking if an Element Exists
To check if a specified element exists in the array, you can use the %in%
operator. This returns a boolean value indicating whether the element is present or not.
For example:
11 %in% array1 # returns TRUE
13 %in% array1 # returns FALSE
Finding the Length of an Array
To find the number of elements present in an array, you can use the length()
function.
For example:
length(array1) # returns 12
This indicates that array1
has 12 elements, spread across two 2×3 matrices.