Convert an Object into a Matrix in R Programming - as.matrix() Function
Last Updated :
30 Apr, 2025
Improve
The as.matrix() function within R converts objects of various classes into a matrix. This can be helpful to work with structures of various data that can be converted into the matrix structure so that it becomes easier to analyze.
Syntax:
as.matrix(x)
Parameters:
- x: Object to be converted
Example 1: Convert vector to the matrix using as.matrix()
# Creating a vector
x <- c(1:9)
# Calling as.matrix() Function
as.matrix(x)
Output
[,1] [1,] 1 [2,] 2 [3,] 3 [4,] 4 [5,] 5 [6,] 6 [7,] 7 [8,] 8 [9,] 9
Example 2: Convert a Data Frame to a Matrix
# Calling pre-defined data set
BOD
# Calling as.matrix() Function
as.matrix(BOD)
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 ...
Example 3: Convert a Sparse Matrix to a Dense Matrix
library(Matrix)
# Create a sparse matrix
s_mat <- Matrix(c(0, 0, 0, 0, 0, 0, 1, 2, 0), nrow = 3, ncol = 3)
s_mat
# Convert to a dense matrix
d_mat <- as.matrix(s_mat)
d_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
library(sp)
# Create a SpatialPointsDataFrame
co <- cbind(c(1, 2, 3), c(4, 5, 6))
sdf <- SpatialPointsDataFrame(coords = co, data = data.frame(ID = 1:3))
sdf
# Convert to a matrix of coordinates
c_mat <- as.matrix(co)
c_mat
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