Open In App

Convert an Object into a Matrix in R Programming – as.matrix() Function

Last Updated : 24 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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()

R




# R program to convert an object to 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 Dataframe to the matrix using as.matrix()

R




# R program to convert an object to 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
[6, ] 7 19.8

Example 3: Convert a Sparse Matrix to a Dense Matrix using as.matrix()

R




library(Matrix)
 
# Create a sparse matrix
sparse_mat <- Matrix(c(0, 0, 0, 0, 0, 0, 1, 2, 0), nrow = 3, ncol = 3)
sparse_mat
# Convert to a dense matrix
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)
 
# Create a SpatialPointsDataFrame
coordinates <- cbind(c(1, 2, 3), c(4, 5, 6))
sdf <- SpatialPointsDataFrame(coords = coordinates, data = data.frame(ID = 1:3))
sdf
# Convert to a matrix of coordinates
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

Similar Reads