How to Convert Matrix to Data Frame in R (With Examples)

In R, it is possible to convert a matrix into a data frame by using an apply function and the as.data.frame() command. The apply function can be used to apply a given function to the rows or columns of the matrix. The as.data.frame() command creates a data frame from the given matrix. This can be done with the help of simple examples. For example, a matrix can be converted to a data frame by using the apply() and as.data.frame() commands as follows: dataframe <- as.data.frame(apply(matrix,2,as.numeric)) where matrix is the matrix to be converted. The resulting data frame can then be manipulated as desired.


You can use one of the following two methods to convert a matrix to a data frame in R:

Method 1: Convert Matrix to Data Frame Using Base R

#convert matrix to data frame
df <- as.data.frame(mat)

#specify column names
colnames(df) <- c('first', 'second', 'third', ...)

Method 2: Convert Matrix to Data Frame Using Tibble Package

library(tibble)

#convert matrix to data frame and specify column names
df <- mat %>%
  as_tibble() %>%
  setNames(c('first', 'second', 'third', ...))

The following examples show how to use each method in practice with the following matrix in R:

#create matrix
mat <- matrix(1:21, nrow=7)

#view matrix
mat

     [,1] [,2] [,3]
[1,]    1    8   15
[2,]    2    9   16
[3,]    3   10   17
[4,]    4   11   18
[5,]    5   12   19
[6,]    6   13   20
[7,]    7   14   21

Example 1: Convert Matrix to Data Frame Using Base R

The following code shows how to convert a matrix to a data frame using base R:

#convert matrix to data frame
df <- as.data.frame(mat)

#specify columns of data frame
colnames(df) <- c('first', 'second', 'third')

#view structure of data frame
str(df)

'data.frame':	7 obs. of  3 variables:
 $ first : int  1 2 3 4 5 6 7
 $ second: int  8 9 10 11 12 13 14
 $ third : int  15 16 17 18 19 20 21

From the output we can see that the matrix has been converted to a data frame with seven observations (rows) and 3 variables (columns).

Example 2: Convert Matrix to Data Frame Using Tibble Package

The following code shows how to convert a matrix to a in R:

library(tibble)

#convert matrix to tibble
df <- mat %>%
  as_tibble() %>%
  setNames(c('first', 'second', 'third'))

#view tibble
df

# A tibble: 7 x 3
  first second third
     
1     1      8    15
2     2      9    16
3     3     10    17
4     4     11    18
5     5     12    19
6     6     13    20
7     7     14    21

From the output we can see that the matrix has been converted to a tibble with 7 rows and 3 columns.

Note: There are many benefits to using tibbles instead of data frames, especially with extremely large datasets. Read about some of the benefits .

x