In R, arrays are multi-dimensional data structures that can hold elements of the same type. They are an extension of matrices, which are 2-dimensional arrays, to more dimensions. Arrays are useful for storing and manipulating data that can be organized into several dimensions, such as time series, images, or multi-dimensional tables.
Creating and Using Arrays in R
1. Creating an Array
You can create an array using the array() function. The basic syntax is:
array(data, dim)
# Create a 1D array with 5 elements
data <- 1:5
array_1d <- array(data, dim = c(5))
print(array_1d)
[1] 1 2 3 4 5
# Create a 2D array with dimensions 2x3
data <- 1:6
array_2d <- array(data, dim = c(2, 3))
print(array_2d)
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
# Create two vectors nof different lengths
vector1 <- c(1,2,3)
vector2 <- c(10,11,12,13,14,15)
#take these vector as input to the array
result <- array(c(vector1,vector2) , dim = c(3,3,2))
print(result)
, , 1
[,1] [,2] [,3]
[1,] 1 10 13
[2,] 2 11 14
[3,] 3 12 15
, , 2
[,1] [,2] [,3]
[1,] 1 10 13
[2,] 2 11 14
[3,] 3 12 15
Naming columns and rows
# Define vectors
vector3 <- c(1, 2, 3)
vector4 <- c(10, 11, 12, 13, 14, 15)
# Define dimension names
column.names <- c("col1", "col2", "col3")
row.names <- c("row1", "row2", "row3")
matrix.names <- c("matrix1", "matrix2")
# Create the 3D array
result <- array(c(vector3, vector4), dim = c(3, 3, 2), dimnames = list(row.names, column.names, matrix.names))
# Print the result
print(result)
, , matrix1
col1 col2 col3
row1 1 2 3
row2 10 11 12
row3 13 14 15
, , matrix2
col1 col2 col3
row1 1 2 3
row2 10 11 12
row3 13 14 15
#print the third row of the second matrix of the array
print(result[3,,2])
col1 col2 col3
3 12 15
#print th element in 1st row 3rd column of 1st matrix
> print(result[1,3,1])
[1] 13
# print the 2nd matrix
print(result[,,2])
col1 col2 col3
row1 1 10 13
row2 2 11 14
row3 3 12 15
No comments:
Post a Comment