Matrices and Arrays as Vectors
In R, matrices and arrays are internally stored as vectors. This means they can be treated like vectors in many operations.
Matrices as Vectors:
A matrix is just a vector with a dimension attribute (dim). If you remove the dimensions, it behaves like a regular vector. The function as.vector() is used to convert a matrix into a vector.
Syntax:
as.vector(matrix)
Example:
> m <- matrix(1:9, nrow = 3, ncol = 3)
> print(m)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> # Converting a Matrix to a Vector
> v <- as.vector(m)
> print(v)
[1] 1 2 3 4 5 6 7 8 9
> # Converting a Matrix to a Vector by Removing Dimensions
> dim(m) <- NULL
> print(m)
[1] 1 2 3 4 5 6 7 8 9
Arrays as Vectors:
An array is a multi-dimensional vector. It behaves like a vector when dimensions are removed. The function as.vector() is used to convert an array into a vector.
Syntax:
as.vector(array)
Example:
> a <- array(1:12, dim = c(2, 3, 2))
> print(a)
, , 1
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
, , 2
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12
> # Converting an Array to a Vector
> v <- as.vector(a)
> print(v)
[1] 1 2 3 4 5 6 7 8 9 10 11 12
> # Removing Dimensions
> dim(a) <- NULL
> print(a)
[1] 1 2 3 4 5 6 7 8 9 10 11 12