# Convert Matrix to DataFrame in R

To convert a Matrix to a DataFrame in R using the as.data.frame() function:

`df <- as.data.frame(my_matrix)`

## Example 1: Convert Matrix to DataFrame

Here we convert a matrix with 3 rows and 2 columns to a DataFrame (note that the class function was used to check the object type before and after the conversion):

```# Create a matrix
my_matrix <- matrix(data = c(12, 15, 18, 23, 25, 27), nrow = 3, ncol = 2)

# Print the class and the matrix
print(class(my_matrix))
print(my_matrix)

# Convert the matrix to a dataframe
df <- as.data.frame(my_matrix)

# Print the class and the dataframe
print(class(df))
print(df)```

Highlighted in yellow is the original matrix. And highlighted in green is the DataFrame after the conversion:

``````"matrix" "array"

[,1] [,2]
[1,]   12   23
[2,]   15   25
[3,]   18   27

"data.frame"

V1 V2
1 12 23
2 15 25
3 18 27``````

## Example 2: Convert Matrix to DataFrame and Assign Column Names

You can use the colnames() function to assign new columns names to the DataFrame:

```# Create a matrix
my_matrix <- matrix(data = c(12, 15, 18, 23, 25, 27), nrow = 3, ncol = 2)

# Print the class and the matrix
print(class(my_matrix))
print(my_matrix)

# Convert the matrix to a dataframe
df <- as.data.frame(my_matrix)

# Assign column names
colnames(df) <- c("Col_A", "Col_B")

# Print the class and the dataframe
print(class(df))
print(df)```

The new column names in the DataFrame are “Col_A” and “Col_B” (highlighted in yellow):

``````"matrix" "array"

[,1] [,2]
[1,]   12   23
[2,]   15   25
[3,]   18   27

"data.frame"

Col_A   Col_B
1    12      23
2    15      25
3    18      27``````

The following tutorial explains how to convert DataFrame to Matrix in R.

Categories R