Convert a Data Frame into a Numeric Matrix in R Programming – data. matrix() Function. data. matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix.
To convert columns of an R data frame from integer to numeric we can use lapply function. For example, if we have a data frame df that contains all integer columns then we can use the code lapply(df,as. numeric) to convert all of the columns data type into numeric data type.
You can do so with the "as. matrix" function. e.g.
A two-dimensional rectangular array to store data in rows and columns is called python matrix. Matrix is a Numpy array to store data in rows and columns. Using dataframe. to_numpy() method we can convert dataframe to Numpy Matrix.
Edit 2: See @flodel's answer. Much better.
Try:
# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))
Edit: or as @ CarlWitthoft suggested in the comments:
matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))
data.matrix(SFI)
From ?data.matrix
:
Description:
Return the matrix obtained by converting all the variables in a
data frame to numeric mode and then binding them together as the
columns of a matrix. Factors and ordered factors are replaced by
their internal codes.
Here is an alternative way if the data frame just contains numbers.
apply(as.matrix.noquote(SFI),2,as.numeric)
but the most reliable way of converting a data frame to a matrix is using data.matrix()
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With