In R, you can convert data frames to matrices using the as.matrix()
function. This function transforms the data frame into a matrix by retaining the original data structure.
In this example,
df
containing three columns: col1
, col2
, and col3
.as.matrix()
function to convert the data frame df
into a matrix named mat
.mat
to the console to verify the conversion.df <- data.frame(col1 = c(1, 2, 3), col2 = c(4, 5, 6), col3 = c(7, 8, 9))
mat <- as.matrix(df)
print(mat)
col1 col2 col3 [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9
In this example,
df
containing two columns: name
and age
. The age
column is a factor.as.matrix()
function to convert the data frame df
into a matrix named mat
.mat
to the console to verify the conversion.df <- data.frame(name = c('Alice', 'Bob', 'Charlie'), age = factor(c('Young', 'Middle', 'Old')))
mat <- as.matrix(df)
print(mat)
name age [1,] "Alice" "Young" [2,] "Bob" "Middle" [3,] "Charlie" "Old"
In this tutorial, we learned How to Convert Data Frames to Matrices in R language with well detailed examples.