VOOZH about

URL: https://www.geeksforgeeks.org/r-language/convert-an-object-into-a-matrix-in-r-programming-as-matrix-function/

⇱ Convert an Object into a Matrix in R Programming - as.matrix() Function - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 30 Apr, 2025

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


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


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

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

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

Comment

Explore