Convert an Object into a Matrix in R Programming – as.matrix() Function
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
Please Login to comment...