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:
df1 = data.frame(
"Name" = c( "Amar" , "Akbar" , "Ronald" ),
"Language" = c( "R" , "Python" , "C#" ),
"Age" = c( 26 , 38 , 22 )
)
print (df1)
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:
df < - data.frame(sample(LETTERS[ 1 : 4 ], 8 ,
replace = T), cbind( 1 : 4 , 1 : 8 ))
colnames(df) < - c( "x" , "y" , "z" )
print (df)
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
16 Jun, 2020
Like Article
Save Article