Convert a Data Frame into a Numeric Matrix in R Programming – data.matrix() Function
Last Updated :
16 Jun, 2020
Improve
data.matrix()
function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix.
Syntax: data.matrix(df)
Parameters:
df: Data frame to be converted.
Example 1:
# R program to convert a data frame # into a numeric matrix # Creating a dataframe df1 = data.frame( "Name" = c( "Amar" , "Akbar" , "Ronald" ), "Language" = c( "R" , "Python" , "C#" ), "Age" = c( 26 , 38 , 22 ) ) # Printing data frame print (df1) # Converting into numeric matrix df2 < - data.matrix(df1) df2 |
Output:
Name Language Age 1 Amar R 26 2 Akbar Python 38 3 Ronald C# 22 Name Language Age [1, ] 2 3 26 [2, ] 1 2 38 [3, ] 3 1 22
Example 2:
# R program to convert a data frame # into a numeric matrix # Creating a dataframe df < - data.frame(sample(LETTERS[ 1 : 4 ], 8 , replace = T), cbind( 1 : 4 , 1 : 8 )) colnames(df) < - c( "x" , "y" , "z" ) # Printing data frame print (df) # Converting into numeric matrix df2 < - data.matrix(df) df2 |
Output:
x y z 1 A 1 1 2 D 2 2 3 C 3 3 4 A 4 4 5 B 1 5 6 B 2 6 7 A 3 7 8 C 4 8 x y z [1, ] 1 1 1 [2, ] 4 2 2 [3, ] 3 3 3 [4, ] 1 4 4 [5, ] 2 1 5 [6, ] 2 2 6 [7, ] 1 3 7 [8, ] 3 4 8