Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 27 Oct, 2021

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
Recommended Articles
Page :

Start Your Coding Journey Now!