Skip to content
Related Articles

Related Articles

Improve Article

Convert Matrix to Dataframe in R

  • Last Updated : 09 May, 2021

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 elements
matrix_data=matrix(c(1,2,3,4,5,6,7,8),nrow=4)
  
# display the data
print(matrix_data)
  
# convert the matrix into dataframe
dataframe_data=as.data.frame(matrix_data)
  
# print dataframe data
print(dataframe_data)

Output:

Example 2:

R




# create the matrix with 8 rows 
# with numeric elements
matrix_data=matrix(c(1,2,3,4,5,6,7,8,11:18),nrow=8)
  
# display the data
print(matrix_data)
  
# convert the matrix into dataframe
dataframe_data=as.data.frame(matrix_data)
  
# print dataframe data
print(dataframe_data)

Output:

Example 3:

R




# create the matrix with 8 rows 
# with different elements
matrix_data=matrix(c(
  "bobby","pinkey","rohith","gnanesh",5.3,6.6,7,8,11:18),nrow=8)
  
# display the data
print(matrix_data)
  
# convert the matrix into dataframe
dataframe_data=as.data.frame(matrix_data)
  
# print dataframe data
print(dataframe_data)

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :