Convert Matrix to Data Frame in R
To convert a matrix to a data frame in R, pass the matrix to as.data.frame(). Each matrix column becomes a data-frame column, and the matrix values keep their existing order unless you explicitly transpose the matrix with t().
A matrix stores all elements using one common data type, while a data frame stores data in separate columns and can later support different types in different columns. Converting a matrix is useful when you need column-based operations, named variables, data-frame methods, or compatibility with functions that expect a data frame.
R as.data.frame() Syntax for Matrix Conversion
To convert Matrix to Data frame in R, use as.data.frame() function. The syntax of as.data.frame() function is
as.data.frame(x, row.names = NULL, optional = FALSE,
make.names = TRUE, …,
stringsAsFactors = default.stringsAsFactors())
Here, x is the matrix to convert. The row.names argument can be used to assign row names to the resulting data frame. For a matrix, the most commonly used form is simply as.data.frame(x).
You can also provide row names to the data frame using row.names.
Convert an R Matrix Without Changing Its Orientation
When a matrix is passed directly to as.data.frame(), its rows and columns remain in the same positions. A matrix with five rows and three columns becomes a data frame with five rows and three columns.
Mat1 <- matrix(
c(1, 5, 14, 23, 54,
9, 15, 85, 3, 42,
9, 7, 42, 87, 16),
ncol = 3
)
DF1 <- as.data.frame(Mat1)
DF1
V1 V2 V3
1 1 9 9
2 5 15 7
3 14 85 42
4 23 3 87
5 54 42 16
Because the matrix has no column names, R assigns the default data-frame names V1, V2, and V3.
Example 1 – Convert Matrix to Data Frame in R
In this example, we will take a simple scenario wherein we create a matrix and convert the matrix to a data frame.
> Mat1 = matrix(c(1, 5, 14, 23, 54, 9, 15, 85, 3, 42, 9, 7, 42, 87, 16), ncol=3)
> Mat1
[,1] [,2] [,3]
[1,] 1 9 9
[2,] 5 15 7
[3,] 14 85 42
[4,] 23 3 87
[5,] 54 42 16
> DF2 = as.data.frame(t(Mat1))
> DF2
V1 V2 V3 V4 V5
1 1 5 14 23 54
2 9 15 85 3 42
3 9 7 42 87 16
>
In this example, t(Mat1) transposes the matrix before conversion. Therefore, the original five-row, three-column matrix becomes a three-row, five-column data frame. The change in orientation is caused by t(), not by as.data.frame().
If you do not want to swap rows and columns, use as.data.frame(Mat1) without t().
Example 2 – Convert Matrix to Data Frame with Column Names
In this example, we create a matrix, and convert this matrix to a data frame with row names.
> Mat1 = matrix(c(1, 5, 14, 23, 54, 9, 15, 85, 3, 42, 9, 7, 42, 87, 16), ncol=3)
> Mat1
[,1] [,2] [,3]
[1,] 1 9 9
[2,] 5 15 7
[3,] 14 85 42
[4,] 23 3 87
[5,] 54 42 16
> DF2 = as.data.frame(t(Mat1), row.names= c('name1', 'name2', 'name3'))
> DF2
V1 V2 V3 V4 V5
name1 1 5 14 23 54
name2 9 15 85 3 42
name3 9 7 42 87 16
>
The row.names argument assigns name1, name2, and name3 to the three rows created after transposing the matrix. Despite the original heading, this example assigns row names rather than column names.
Convert an R Matrix to a Data Frame with Column Names
To control the column names of the resulting data frame, assign column names to the matrix before conversion or rename the data-frame columns afterward.
scores <- matrix(
c(82, 91, 76, 88, 85, 90),
nrow = 3,
ncol = 2
)
colnames(scores) <- c("Mathematics", "Science")
score_df <- as.data.frame(scores)
score_df
Mathematics Science
1 82 88
2 91 85
3 76 90
The matrix column names are retained as data-frame column names. You can also rename them after conversion with names() or colnames().
names(score_df) <- c("Math_Score", "Science_Score")
Convert an R Matrix to a Data Frame with Row Names
If the matrix already has row names, as.data.frame() normally preserves them.
rownames(scores) <- c("Asha", "Ravi", "Meera")
score_df <- as.data.frame(scores)
score_df
Mathematics Science
Asha 82 88
Ravi 91 85
Meera 76 90
You can inspect the resulting labels with rownames(score_df) and names(score_df).
Use as.data.frame() or data.frame() for an R Matrix
Both as.data.frame(matrix_object) and data.frame(matrix_object) can create a data frame from a matrix, but as.data.frame() expresses the conversion directly and generally preserves the matrix dimensions and dimension names in a predictable way.
| Method | Typical use | Result |
|---|---|---|
as.data.frame(x) | Convert an existing matrix object | Each matrix column becomes one data-frame column |
data.frame(x) | Build a data frame from one or more objects | A data frame is constructed from the supplied inputs |
as.data.frame(t(x)) | Convert after swapping rows and columns | The transposed matrix becomes the data frame |
How Matrix Data Types Behave After Conversion
Every matrix has one underlying data type. Therefore, all columns in the initial data frame usually begin with that same type after conversion.
- A numeric matrix produces numeric data-frame columns.
- An integer matrix produces integer data-frame columns.
- A character matrix produces character data-frame columns.
- A logical matrix produces logical data-frame columns.
After conversion, individual data-frame columns can be changed independently because a data frame can store a different type in each column.
result <- as.data.frame(matrix(c("101", "102", "yes", "no"), ncol = 2))
result$V1 <- as.integer(result$V1)
result$V2 <- result$V2 == "yes"
str(result)
'data.frame': 2 obs. of 2 variables:
$ V1: int 101 102
$ V2: logi TRUE FALSE
Convert a Matrix to a Long-Format Data Frame in R
A direct conversion keeps the matrix in wide format. When each matrix cell must become a separate row, create a long-format data frame containing the row identifier, column identifier, and value.
measurements <- matrix(
c(10, 12, 14, 20, 22, 24),
nrow = 3,
dimnames = list(
c("Item1", "Item2", "Item3"),
c("Before", "After")
)
)
long_df <- as.data.frame(as.table(measurements))
names(long_df) <- c("Item", "Stage", "Value")
long_df
Item Stage Value
1 Item1 Before 10
2 Item2 Before 12
3 Item3 Before 14
4 Item1 After 20
5 Item2 After 22
6 Item3 After 24
This format is useful when row and column positions represent categories that should be stored as regular variables.
Verify the Matrix-to-Data-Frame Result in R
After conversion, check the class, dimensions, column names, row names, and column types before continuing with analysis.
is.data.frame(score_df)
dim(score_df)
names(score_df)
rownames(score_df)
str(score_df)
is.data.frame()confirms that the object is a data frame.dim()verifies the number of rows and columns.names()returns the data-frame column names.rownames()returns the row labels.str()shows the type of each data-frame column.
Common R Matrix-to-Data-Frame Conversion Problems
- The rows and columns are reversed: Check whether the matrix was passed through
t(). Removet()when no transpose is required. - The columns are named V1, V2, and V3: The source matrix had no column names. Assign them with
colnames()before conversion or rename the data-frame columns afterward. - Expected row names are missing: Assign row names to the matrix with
rownames()or supply therow.namesargument during conversion. - All columns have the same type: This reflects the matrix’s single underlying type. Convert individual columns after creating the data frame when different types are required.
- The result has unexpected dimensions: Compare
dim(matrix_object)withdim(data_frame_object)and check for any prior transpose or subsetting operation.
Frequently Asked Questions about Converting an R Matrix to a Data Frame
How do I convert a matrix to a data frame in R?
Use as.data.frame(my_matrix). Each matrix column becomes one data-frame column, and the matrix dimensions remain unchanged.
How do I keep matrix column names in the R data frame?
Assign column names with colnames(my_matrix) before calling as.data.frame(). Existing matrix column names are normally retained.
Why does my converted data frame look transposed?
The matrix was probably passed to t() before conversion. The expression as.data.frame(t(x)) transposes the matrix, while as.data.frame(x) keeps the original orientation.
How do I rename columns after converting a matrix in R?
Use names(df) <- c(...) or colnames(df) <- c(...), making sure the number of supplied names matches the number of data-frame columns.
How do I convert a matrix into a long data frame?
For a matrix with row and column labels, use as.data.frame(as.table(x)). This creates one row per matrix cell with separate row-label, column-label, and value columns.
R Matrix-to-Data-Frame Editorial QA Checklist
- Confirm that examples distinguish direct conversion from conversion after
t(). - Verify that stated row and column counts match the displayed matrix and data frame.
- Check whether examples assign row names or column names and label them correctly.
- Confirm that output column names match the source matrix dimension names or R’s default
V1naming. - Run each R example and verify the resulting class, dimensions, values, and column types.
Summary of R Matrix-to-Data-Frame Conversion
Use as.data.frame(matrix_object) to convert an R matrix without changing its orientation. Assign matrix row names and column names before conversion when those labels must be retained. Use t() only when rows and columns intentionally need to be swapped, and inspect the final structure with dim(), names(), and str().
In this R Tutorial, we have learnt to convert a matrix to a data frame, with the help of examples.
TutorialKart.com