Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

as.matrix() function in R Programming Language 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
My Personal Notes arrow_drop_up
Last Updated : 27 Oct, 2021
Like Article
Save Article
Similar Reads