Convert Data Frame to Matrix in R

To convert a data frame to a matrix in R, use data.matrix() when you need a numeric matrix, or as.matrix() when you want R to preserve compatible values and apply its standard type-coercion rules.

This conversion is useful when a function expects a matrix, when you need matrix multiplication or transposition, or when you want to pass tabular data to numerical routines. Because every element of an R matrix must have the same data type, it is important to check how numeric, factor, character, logical, and date columns are converted.

R data.matrix() Syntax for Data Frame Conversion

To convert Dataframe to Matrix in R language, use data.matrix() method. The syntax of data.matrix() method is

</>
Copy
 data.matrix(frame, rownames.force = NA)

where frame is the dataframe and rownames.force is logical indicating if the resulting matrix should have character (rather than NULLrownames. The default, NA, uses NULL rownames if the data frame has ‘automatic’ row.names or for a zero-row data frame.

The data.matrix() function attempts to create a numeric matrix. Numeric and integer columns remain numeric, logical values become numeric values, and factor columns are replaced by their internal integer codes. Other non-numeric columns are converted using R’s numeric conversion rules.

Example 1 – Convert Data Frame to Matrix in R

In this example, we will create an R dataframe and then convert it to a matrix.

</>
Copy
> DF1 = data.frame(c1= c(1, 5, 14, 23, 54), c2= c(9, 15, 85, 3, 42), c3= c(9, 7, 42, 87, 16))
> DF1
  c1 c2 c3
1  1  9  9
2  5 15  7
3 14 85 42
4 23  3 87
5 54 42 16
> Mat1 = data.matrix(DF1)
> Mat1
     c1 c2 c3
[1,]  1  9  9
[2,]  5 15  7
[3,] 14 85 42
[4,] 23  3 87
[5,] 54 42 16

The result is a numeric matrix with the original data-frame column names. The automatically generated row names are not included because the data frame uses ordinary sequential row names.

Convert a Data Frame to a Matrix with Row Names

Set rownames.force = TRUE when the matrix must retain row names. This is useful when each row represents a named observation, product, student, location, or other identifiable record.

</>
Copy
scores <- data.frame(
  mathematics = c(82, 91, 76),
  science = c(88, 85, 90),
  row.names = c("Arun", "Beena", "Charan")
)

score_matrix <- data.matrix(scores, rownames.force = TRUE)
score_matrix
       mathematics science
Arun            82      88
Beena           91      85
Charan           76      90

Column names are normally retained automatically. You can inspect the resulting labels with rownames(score_matrix) and colnames(score_matrix).

data.matrix() and as.matrix() in R

Both functions can turn a data frame into a matrix, but they handle mixed column types differently.

FunctionTypical resultUse it when
data.matrix()Attempts to produce a numeric matrixYou need numeric values for calculations or statistical routines
as.matrix()Produces one common matrix type; mixed numeric and character data usually becomes characterYou need a general matrix representation and character values are acceptable

For example, a data frame containing a character column cannot remain partly numeric and partly character after conversion. With as.matrix(), R commonly converts every value to character so that the matrix has one consistent type.

</>
Copy
employees <- data.frame(
  name = c("Asha", "Ravi"),
  experience = c(4, 7)
)

employee_matrix <- as.matrix(employees)
employee_matrix
class(employee_matrix)
     name   experience
[1,] "Asha" "4"
[2,] "Ravi" "7"

[1] "matrix" "array"

In this result, the numeric values appear as character strings because the matrix also contains employee names.

Convert a Mixed Data Frame to a Numeric Matrix

When only some columns are suitable for numerical calculations, select those columns before converting the data frame. This avoids accidental conversion of identifiers or descriptive text.

</>
Copy
sales <- data.frame(
  product = c("Pen", "Book", "Bag"),
  units = c(20, 12, 8),
  price = c(1.5, 6.0, 18.5)
)

numeric_sales <- data.matrix(sales[c("units", "price")])
numeric_sales
     units price
[1,]    20   1.5
[2,]    12   6.0
[3,]     8  18.5

You can also select numeric columns automatically with vapply().

</>
Copy
numeric_columns <- vapply(sales, is.numeric, logical(1))
numeric_sales <- data.matrix(sales[, numeric_columns, drop = FALSE])

The argument drop = FALSE ensures that the selected object remains a data frame even when only one numeric column is found.

Factor Columns in an R Numeric Matrix

A factor column is converted to its internal integer level codes by data.matrix(). These codes do not necessarily represent meaningful numeric measurements.

</>
Copy
survey <- data.frame(
  rating = factor(c("low", "high", "medium"),
                  levels = c("low", "medium", "high")),
  score = c(52, 91, 73)
)

data.matrix(survey)
     rating score
[1,]      1    52
[2,]      3    91
[3,]      2    73

Here, low, medium, and high become 1, 2, and 3 according to the factor-level order. Inspect factor levels with levels(survey$rating) before treating these codes as ordered numeric values.

Convert a Tibble to a Matrix in R

A tibble can be converted with the same base R functions because it is built on the data-frame structure. Use as.matrix() for a general conversion or data.matrix() when the selected columns should form a numeric matrix.

</>
Copy
library(tibble)

measurements <- tibble(
  length = c(10.2, 11.5, 9.8),
  width = c(4.1, 4.6, 3.9)
)

measurement_matrix <- data.matrix(measurements)
measurement_matrix

Tibbles do not normally use custom row names. Store identifiers in a regular column, or explicitly assign row names after conversion when the receiving function requires them.

Verify the Converted R Matrix

After conversion, inspect the object type, dimensions, storage mode, and labels before using it in calculations.

</>
Copy
is.matrix(Mat1)
dim(Mat1)
typeof(Mat1)
rownames(Mat1)
colnames(Mat1)
  • is.matrix() confirms that the result is a matrix.
  • dim() returns the number of rows and columns.
  • typeof() shows the underlying storage type, such as double or character.
  • rownames() and colnames() show the matrix labels.

Common Data Frame-to-Matrix Conversion Problems

  • Every value becomes character: The data frame contains at least one character column and was converted with as.matrix(). Select only numeric columns or use an appropriate encoding method.
  • Factor values become unexpected numbers: data.matrix() uses factor-level codes. Check the factor levels before interpreting the result.
  • Row names disappear: Use meaningful data-frame row names and set rownames.force = TRUE.
  • Missing values remain in the matrix: Conversion does not automatically remove or replace NA. Handle missing values according to the intended calculation.
  • A single selected column becomes a vector: Use drop = FALSE while subsetting so that the input remains two-dimensional.

Frequently Asked Questions about R Data Frame to Matrix Conversion

How do I turn a data frame into a matrix in R?

Use data.matrix(my_data_frame) for a numeric matrix. Use as.matrix(my_data_frame) when a general common-type conversion is acceptable.

How do I convert an R data frame to a matrix with row names?

Assign meaningful row names to the data frame and call data.matrix(df, rownames.force = TRUE). You can confirm them with rownames().

Why does as.matrix() convert numeric columns to character?

A matrix can contain only one common data type. When a data frame contains both character and numeric columns, as.matrix() generally converts all elements to character.

How do I create a numeric matrix from only numeric data-frame columns?

Select the required numeric columns before conversion, or identify them with vapply(df, is.numeric, logical(1)). Then pass the resulting data frame to data.matrix().

Can I convert a tibble to a matrix?

Yes. Use data.matrix(tibble_object) for numeric tibble columns or as.matrix(tibble_object) for a general conversion.

R Data Frame to Matrix Editorial QA Checklist

  • Confirm whether the example requires data.matrix() or as.matrix().
  • Check that mixed character and numeric columns are not presented as a numeric matrix without explanation.
  • Verify factor-level ordering before describing factor codes as numeric values.
  • Confirm that row names and column names in each output match the corresponding input.
  • Run each R example and verify its dimensions, values, and displayed output.

Summary of Converting Data Frames to Matrices in R

Use data.matrix() when an R data frame must become a numeric matrix. Use as.matrix() when you need a general matrix and understand that mixed columns may force the entire result to character. Before conversion, select appropriate columns and inspect factor, character, row-name, and missing-value behavior.

In this R Tutorial, we have learnt to convert Data Frame to Matrix.