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


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 tibble 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 here.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Convert Matrix to Vector in R
How to Convert Data Frame to Matrix in R
How to Convert List to Matrix in R

Leave a Reply

Your email address will not be published. Required fields are marked *