Convert DataFrame to Matrix in R

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

mat <- as.matrix(df)

For example:

# Create a DataFrame
df <- data.frame(
  col_a = c(1, 2, 3),
  col_b = c(4, 5, 6),
  col_c = c(7, 8, 9)
)

# Convert the DataFrame to a Matrix in R
mat <- as.matrix(df)

# Print the Matrix
print(mat)

The resulted Matrix after the conversion:

     col_a  col_b  col_c
[1,]     1      4      7
[2,]     2      5      8
[3,]     3      6      9

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

Leave a Comment