Convert Matrix to Data Frame in R

In this tutorial, we will learn how to convert a matrix to a data frame in R programming.

To convert Matrix to Data frame in R, use as.data.frame() function. The syntax of as.data.frame() function is

as.data.frame(x, row.names = NULL, optional = FALSE,
              make.names = TRUE, …,
              stringsAsFactors = default.stringsAsFactors())

You can also provide row names to the data frame using row.names.

Example 1 – Convert Matrix to Data Frame in R

In this example, we will take a simple scenario wherein we create a matrix and convert the matrix to a data frame.

> Mat1 = matrix(c(1, 5, 14, 23, 54, 9, 15, 85, 3, 42, 9, 7, 42, 87, 16), ncol=3)
> Mat1
     [,1] [,2] [,3]
[1,]    1    9    9
[2,]    5   15    7
[3,]   14   85   42
[4,]   23    3   87
[5,]   54   42   16
> DF2 = as.data.frame(t(Mat1))
> DF2
  V1 V2 V3 V4 V5
1  1  5 14 23 54
2  9 15 85  3 42
3  9  7 42 87 16
>

You might be quizzed that the Data frame looks like the transposed version of the Matrix. But, it is totally fine. It is just that these two data objects: matrix and data frame are represented differently.

ADVERTISEMENT

Example 2 – Convert Matrix to Data Frame with Column Names

In this example, we create a matrix, and convert this matrix to a data frame with row names.

> Mat1 = matrix(c(1, 5, 14, 23, 54, 9, 15, 85, 3, 42, 9, 7, 42, 87, 16), ncol=3)
> Mat1
     [,1] [,2] [,3]
[1,]    1    9    9
[2,]    5   15    7
[3,]   14   85   42
[4,]   23    3   87
[5,]   54   42   16
> DF2 = as.data.frame(t(Mat1), row.names= c('name1', 'name2', 'name3'))
> DF2
      V1 V2 V3 V4 V5
name1  1  5 14 23 54
name2  9 15 85  3 42
name3  9  7 42 87 16
>

Conclusion

In this R Tutorial, we have learnt to convert a matrix to a data frame, with the help of examples.