R Array
Arrays are also objects in R, and R can create one-dimensional or multi-dimensional arrays.
An R array is a collection of the same type. The matrix we learned earlier is actually a two-dimensional array.
The relationship between vectors, matrices, and arrays can be seen in the following diagram:
!(#)
R arrays are created using the `array()` function. This function takes a vector as input and can use `dim` to set the array dimensions.
The syntax for the `array()` function is as follows:
`array(data = NA, dim = length(data), dimnames = NULL)`
**Parameter Description:**
* **data** - Specifies the data source for the array. It can be a vector, matrix, or list.
* **dim** - Specifies the dimensions of the array. It can be an integer vector or a tuple representing dimensions. The default is a one-dimensional array. For example, `dim = c(2, 3, 4)` creates a **2x3x4** three-dimensional array.
* **dimnames** - An optional parameter used to specify the names for each dimension of the array. It can be a list containing dimension names.
In R, array indexing starts from 1, which differs from the convention in other programming languages.
Additionally, R provides a rich set of functions and operators for handling array data, such as indexing, slicing, reshaping, aggregation, etc.
In R, you can use (#) or (#) to represent multi-dimensional arrays.
**Matrix:** The matrix is the most common form of representing arrays in R. It is a two-dimensional structure with a fixed number of rows and columns.
You can use the `matrix()` function to create a matrix, specifying the data elements and dimensions.
## Example
# Create a 3x3 matrix
my_matrix <-matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow=3, ncol=3)
print(my_matrix)
**List:** A list is a more general form of multi-dimensional array in R. It can contain elements of different types, and each element can be a matrix, vector, or other data structure.
## Example
# Create a list containing a matrix and a vector
my_list <-list(matrix(c(1, 2, 3, 4), nrow=2), c(5, 6, 7))
print(my_list)
## Example
# Create a list containing a matrix and a vector
my_list <-list(matrix(c(1, 2, 3, 4), nrow=2), c(5, 6, 7))
print(my_list)
Besides matrices and lists, R also provides other data structures to represent multi-dimensional arrays, such as Array and Data Frame.
### Example
Here are some examples demonstrating the use of the **`array()`** function:
Create a one-dimensional array using a vector:
## Example
my_vector <-c(1, 2, 3, 4)
my_array <-array(my_vector, dim=c(4))
print(my_array)
In the following example, we create a two-dimensional array with 3 rows and 3 columns:
## Example
# Create two vectors of different lengths
vector1 <-c(5,9,3)
vector2 <-c(10,11,12,13,14,15)
# Create the array
result <-array(c(vector1,vector2),dim=c(3,3,2))
print(result)
Executing the above code produces the following output:
, , 1
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
, , 2
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
Use the `dimnames` parameter to set the names for each dimension:
## Example
# Create two vectors of different lengths
vector1 <-c(5,9,3)
vector2 <-c(10,11,12,13,14,15)
column.names<-c("COL1","COL2","COL3")
row.names<-c("ROW1","ROW2","ROW3")
matrix.names<-c("Matrix1","Matrix2")
# Create the array and set the names for each dimension
result <-array(c(vector1,vector2),dim=c(3,3,2),dimnames=list(row.names,column.names,matrix.names))
print(result)
Executing the above code produces the following output:
, , Matrix1
COL1 COL2 COL3
ROW1 5 10 13
ROW2 9 11 14
ROW3 3 12 15
, , Matrix2
COL1 COL2 COL3
ROW1 5 10 13
ROW2 9 11 14
ROW3 3 12 15
### Accessing Array Elements
In R, you can use the indexing operator `` to access elements of a multi-dimensional array.
The indexing operator allows you to retrieve specific elements from the array based on specified index positions.
To access an array element, you can use the column index and row index of the element, similar to a coordinate format.
Access a single element:
## Example
my_array <-array(1:12, dim=c(2, 3, 2))# Create a 3D array
element <- my_array[1, 2, 1]# Access the element where the first dimension is 1, the second dimension is 2, and the third dimension is 1
print(element)
Access multiple elements:
## Example
my_array <-array(1:12, dim=c(2, 3, 2))# Create a 3D array
elements <- my_array[c(1, 2), c(2, 3), c(1, 2)]# Access multiple elements, with indices 1 and 2 for each dimension
print(elements)
Access elements of a two-dimensional array:
## Example
# Create two vectors of different lengths
vector1 <-c(5,9,3)
vector2 <-c(10,11,12,13,14,15)
column.names<-c("COL1","COL2","COL3")
row.names<-c("ROW1","ROW2","ROW3")
matrix.names<-c("Matrix1","Matrix2")
# Create the array
result <-array(c(vector1,vector2),dim=c(3,3,2),dimnames=list(row.names, column.names, matrix.names))
# Display the elements of the third row in the second matrix of the array
print(result[3,,2])
# Display the element in the first row and third column of the first matrix of the array
print(result[1,3,1])
# Output the second matrix
print(result[,,2])
Executing the above code produces the following output:
COL1 COL2 COL3
3 12 15
13
COL1 COL2 COL3
ROW1 5 10 13
ROW2 9 11 14
ROW3 3 12 15
Filter using logical conditions:
## Example
my_array <-array(1:12, dim=c(2, 3, 2))# Create a 3D array
filtered_elements 5]# Select elements greater than 5
print(filtered_elements)# Output: 6 7 8 9 10 11 12
### Manipulating Array Elements
Since an array is composed of matrices across multiple dimensions, we can access array elements by accessing the elements of the matrices.
## Example
# Create two vectors of different lengths
vector1 <-c(5,9,3)
vector2 <-c(10,11,12,13,14,15)
# Create the first array
array1 <-array(c(vector1,vector2),dim=c(3,3,2))
# Create two vectors of different lengths
vector3 <-c(9,1,0)
vector4 <-c(6,0,11,3,14,1,2,6,9)
array2 <-array(c(vector3,vector4),dim=c(3,3,2))
# Create matrices from the arrays
matrix1 <- array1[,,2]
matrix2 <- array2[,,2]
# Add the matrices
result <- matrix1+matrix2
print(result)
Executing the above code produces the following output:
[,1] [,2] [,3]
[1,] 7 19 19
[2,] 15 12 14
[3,] 12 12 26
Additionally, we can use the **`apply()`** function to perform cross-dimensional calculations on array elements. The syntax is as follows:
`apply(X, MARGIN, FUN, ...)`
Parameter Description:
* `X`: The array or matrix to which the function will be applied.
* `MARGIN`: Specifies the dimension to which the function will be applied. It can be 1 for rows, 2 for columns, or `c(1, 2)` for both rows and columns simultaneously.
* `FUN`: The function to be applied. It can be a built-in function (like `mean`, `sum`, etc.) or a custom function.
* `...`: Optional parameters to pass to the function.
Below, we use the `apply()` function to calculate the sum of numbers in each row across the two matrices in the array.
## Example
# Create two vectors of different lengths
vector1 <-c(5,9,3)
vector2 <-c(10,11,12,13,14,15)
# Create the array
new.array<-array(c(vector1,vector2),dim=c(3,3,2))
print(new.array)
# Calculate the sum of numbers in the first row of all matrices in the array
result <-apply(new.array, c(1), sum)
print(result)
Executing the above code produces the following output:
, , 1
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
, , 2
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
56 68 60
Apply a built-in function to the rows or columns of a matrix:
## Example
# Create a 3x3 matrix
my_matrix <-matrix(1:9, nrow=3)
# Apply the sum function to each column
col_sums <-apply(my_matrix, 2, sum)
print(col_sums)
Executing the above code produces the following output:
6 15 24
Apply a custom function to the rows or columns of a matrix:
## Example
# Create a 3x3 matrix
my_matrix <-matrix(1:9, nrow=3)
# Custom function: calculate the mean of each row
row_mean <-function(x){
return(mean(x))
}
# Apply the row_mean function to each row
row_means <-apply(my_matrix, 1, row_mean)
print(row_means)
Executing the above code produces the following output:
4 5 6
Apply a function to multiple dimensions of an array simultaneously:
## Example
# Create a 3D array
my_array <-array(1:12, dim=c(2, 3, 2))
# Apply the mean function to the first and third dimensions simultaneously
result <-apply(my_array, c(1, 3), mean)
print(result)
Executing the above code produces the following output:
[,1] [,2]
[1,] 3 9
[2,] 4 10
YouTip