as.matrix() Function in detail
The as.matrix() function in R is used to transform different types of objects into matrices. This is useful when working with structured data that needs to be handled in matrix form.
Syntax:
as.matrix(x)
Parameters:
x: The object that needs to be converted into a matrix.
Examples
Example 1: Converting a Vector to a Matrix
vector_data <- c(5:13)
# Convert the vector to a matrix
matrix_data <- as.matrix(vector_data)
# Print the matrix
print(matrix_data)
Output:
[,1]
[1, ] 5
[2, ] 6
[3, ] 7
[4, ] 8
[5, ] 9
[6, ] 10
[7, ] 11
[8, ] 12
[9, ] 13
Example 2: Converting a Data Frame to a Matrix
# Create a sample data frame
data_frame <- data.frame(Age = c(21, 25, 30, 35), Height = c(160, 170, 175, 180))
# Convert the data frame to a matrix
matrix_df <- as.matrix(data_frame)
# Print the matrix
print(matrix_df)
Properties:
- The total number of columns in the resultant matrix equals the sum of columns from the input matrices.
- Non-Commutative: The order in which matrices are combined matters, meaning
cbind(A, B) ≠ cbind(B, A). - Associative:
cbind(cbind(A, B), C) = cbind(A, cbind(B, C)).
2. Row-Wise Combination
Row binding is done using the rbind() function in R. It merges two matrices, A_(m×p) and B_(n×p), row-wise, as long as they have the same number of columns.
Example:
# Create a sample data frame
data_frame <- data.frame(Age = c(21, 25, 30, 35), Height = c(160, 170, 175, 180))
# Convert the data frame to a matrix
matrix_df <- as.matrix(data_frame)
# Print the matrix
print(matrix_df)
Output:
Age Height
[1,] 21 160
[2,] 25 170
[3,] 30 175
[4,] 35 180
Example 3: Converting a Sparse Matrix to a Dense Matrix
library(Matrix)
# Create a sparse matrix
sparse_matrix <- Matrix(c(0, 3, 0, 0, 0, 7, 5, 0, 0), nrow = 3, ncol = 3)
print(sparse_matrix)
# Convert to a dense matrix
dense_matrix <- as.matrix(sparse_matrix)
print(dense_matrix)
Output:
3 x 3 sparse Matrix of class "dgCMatrix"
[,1] [,2] [,3]
[1,] 0 3 0
[2,] 0 0 7
[3,] 5 0 0
[,1] [,2] [,3]
[1,] 0 3 0
[2,] 0 0 7
[3,] 5 0 0
Example 4: Converting Coordinates to a Matrix
library(sp)
# Define coordinate points
coords <- cbind(c(10, 15, 20), c(25, 30, 35))
# Create a SpatialPointsDataFrame
spatial_df <- SpatialPointsDataFrame(coords = coords, data = data.frame(ID = 1:3))
# Convert the coordinates to a matrix
coord_matrix <- as.matrix(coords)
# Print the matrix
print(coord_matrix)
Output:
[,1] [,2]
[1,] 10 25
[2,] 15 30
[3,] 20 35
Leave a Reply