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

PikkuKatja picture PikkuKatja · May 13, 2013 · Viewed 153.3k times · Source

I have a data frame taken from a .csv-file which contains numeric and character values. I want to convert this data frame into a matrix. All containing information is numbers (the non-number-rows I deleted), so it should be possible to convert the data frame into a numeric matrix. However, I do get a character matrix.

I found the only way to solve this is to use as.numeric for each and every row, but this is quite time-consuming. I am quite sure there is a way to do this with some kind of if(i in 1:n)-form, but I cannot figure out how it might work. Or is the only way really to already start with numeric values, like proposed here(Making matrix numeric and name orders)?

Probably this is a very easy thing for most of you :P

The matrix is a lot bigger, this is only the first few rows... Here's the code:

cbind(
as.numeric(SFI.Matrix[ ,1]),
as.numeric(SFI.Matrix[ ,2]),
as.numeric(SFI.Matrix[ ,3]),
as.numeric(SFI.Matrix[ ,4]),
as.numeric(SFI.Matrix[ ,5]),
as.numeric(SFI.Matrix[ ,6]))  

# to get something like this again:

Social.Assistance Danger.Poverty GINI S80S20 Low.Edu        Unemployment 
0.147             0.125          0.34    5.5   0.149        0.135 0.18683691
0.258             0.229          0.27    3.8   0.211        0.175 0.22329362
0.207             0.119          0.22    3.1   0.139        0.163 0.07170422
0.219             0.166          0.25    3.6   0.114        0.163 0.03638525
0.278             0.218          0.29    4.1   0.270        0.198 0.27407825
0.288             0.204          0.26    3.6   0.303        0.211 0.22372633

Thank you for any help!

Answer

Ricardo Saporta picture Ricardo Saporta · May 13, 2013

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))