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

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


Edit 2: See @flodel's answer. Much better.

Try:

# assuming SFI is your data.frameas.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)