R Arrays
Arrays in R are multi-dimensional data structures that can hold elements of the same data type. They are used to store data in more than two dimensions.
Key Topics
Array Creation
Arrays can be created using the array()
function.
# Creating a 3D array
my_array <- array(1:12, dim = c(3, 2, 2))
print(my_array)
Output:
, , 1
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
, , 2
[,1] [,2]
[1,] 7 10
[2,] 8 11
[3,] 9 12
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
, , 2
[,1] [,2]
[1,] 7 10
[2,] 8 11
[3,] 9 12
Code Explanation: The array()
function creates a 3D array with dimensions 3x2x2 and fills it with values from 1 to 12.
Accessing Array Elements
You can access elements of an array using square brackets with the specified indices.
# Accessing elements
value <- my_array[2, 1, 2]
print(value)
Output:
[1] 8
Code Explanation: The element at position (2, 1, 2) in my_array
is accessed and printed.
Key Takeaways
- Arrays can store data in more than two dimensions.
- The
array()
function is used to create arrays with specified dimensions. - Elements are accessed using indices in square brackets.