Convert an Object into a Matrix in R Programming – as.matrix() Function
Last Updated :
24 Nov, 2023
In R Programming Language as. matrix() function is used to convert an object into a Matrix.
Syntax: as.matrix(x)
Parameters:
- x: Object to be converted
as.matrix() Function in R Example
Example 1: Convert vector to the matrix using as.matrix()
Output:
[, 1]
[1, ] 1
[2, ] 2
[3, ] 3
[4, ] 4
[5, ] 5
[6, ] 6
[7, ] 7
[8, ] 8
[9, ] 9
Example 2: Convert Dataframe to the matrix using as.matrix()
Output:
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
Time demand
[1, ] 1 8.3
[2, ] 2 10.3
[3, ] 3 19.0
[4, ] 4 16.0
[5, ] 5 15.6
[6, ] 7 19.8
Example 3: Convert a Sparse Matrix to a Dense Matrix using as.matrix()
R
library (Matrix)
sparse_mat <- Matrix ( c (0, 0, 0, 0, 0, 0, 1, 2, 0), nrow = 3, ncol = 3)
sparse_mat
dense_mat <- as.matrix (sparse_mat)
dense_mat
|
Output:
3 x 3 sparse Matrix of class "dtCMatrix"
[1,] . . 1
[2,] . . 2
[3,] . . .
[,1] [,2] [,3]
[1,] 0 0 1
[2,] 0 0 2
[3,] 0 0 0
Example 4: Convert a SpatialPointsDataFrame to a Matrix using as.matrix()
R
library (sp)
coordinates <- cbind ( c (1, 2, 3), c (4, 5, 6))
sdf <- SpatialPointsDataFrame (coords = coordinates, data = data.frame (ID = 1:3))
sdf
coord_matrix <- as.matrix (coordinates)
coord_matrix
|
Output:
coordinates ID
1 (1, 4) 1
2 (2, 5) 2
3 (3, 6) 3
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
These examples show the flexibility of the as.matrix()
function in handling different types of objects and conversions in R Programming Language. Depending on our data and requirements, we may need to tailor the conversion process accordingly.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...