Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right way to convert data.frame to a numeric matrix, when df also contains strings?

People also ask

How do you change a Dataframe to a matrix?

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.

How do you convert DF to numeric?

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.

Which function will convert the data to the matrix format?

You can do so with the "as. matrix" function. e.g.

How do you convert a dataset to a matrix in python?

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.