Convert Matrix to Dataframe in R
In this article, we will discuss how to convert the matrix into DataFrame, or we can also say that we will discuss how to create a DataFrame from a matrix in R Programming Language.
A matrix can be converted to a dataframe by using a function called as.data.frame(). It will take each column from the matrix and convert it to each column in the dataframe.
Syntax:
as.data.frame(matrix_data)
Where, matrix_data is the input matrix.
Example 1:
R
# create the matrix with 4 rows # with numeric elementsmatrix_data=matrix(c(1,2,3,4,5,6,7,8),nrow=4) # display the dataprint(matrix_data) # convert the matrix into dataframedataframe_data=as.data.frame(matrix_data) # print dataframe dataprint(dataframe_data) |
Output:
Example 2:
R
# create the matrix with 8 rows # with numeric elementsmatrix_data=matrix(c(1,2,3,4,5,6,7,8,11:18),nrow=8) # display the dataprint(matrix_data) # convert the matrix into dataframedataframe_data=as.data.frame(matrix_data) # print dataframe dataprint(dataframe_data) |
Output:
Example 3:
R
# create the matrix with 8 rows # with different elementsmatrix_data=matrix(c( "bobby","pinkey","rohith","gnanesh",5.3,6.6,7,8,11:18),nrow=8) # display the dataprint(matrix_data) # convert the matrix into dataframedataframe_data=as.data.frame(matrix_data) # print dataframe dataprint(dataframe_data) |
Output:


