Convert Data Frame to Matrix in R

In this tutorial, we will learn how to convert an R Dataframe to an R Matrix.

Consider that you have your data loaded to an R Dataframe and it is required to do some matrix operations on the data. You can load your dataframe into a matrix and do the matrix operations on it.

To convert Dataframe to Matrix in R language, use data.matrix() method. The syntax of data.matrix() method is

data.matrix(frame, rownames.force = NA)

where frame is the dataframe and rownames.force is logical indicating if the resulting matrix should have character (rather than NULLrownames. The default, NA, uses NULL rownames if the data frame has ‘automatic’ row.names or for a zero-row data frame.

Example 1 – Convert Data Frame to Matrix in R

In this example, we will create an R dataframe and then convert it to a matrix.

> DF1 = data.frame(c1= c(1, 5, 14, 23, 54), c2= c(9, 15, 85, 3, 42), c3= c(9, 7, 42, 87, 16))
> DF1
  c1 c2 c3
1  1  9  9
2  5 15  7
3 14 85 42
4 23  3 87
5 54 42 16
> Mat1 = data.matrix(DF1)
> Mat1
     c1 c2 c3
[1,]  1  9  9
[2,]  5 15  7
[3,] 14 85 42
[4,] 23  3 87
[5,] 54 42 16
ADVERTISEMENT

Conclusion

In this R Tutorial, we have learnt to convert Data Frame to Matrix.