Save matrix to .csv file in R without losing format

angry_einstein picture angry_einstein · Dec 9, 2012 · Viewed 10.2k times · Source

I'm trying to write a matrix to a .csv file using the write.matrix from MASS but I'm having some problems. When I print the matrix it look something like this

    p q         s         S2         R2      R2adj          Cp      AIC     PRESS
1   0 1 167.27779 27981.8583         NA         NA 3679.294476       NA        NA
2   1 2 160.32254 25703.3165 0.08866209 0.08142925 3343.909110 1666.993 3338167.3
3   1 2  86.73559  7523.0630 0.73326195 0.73114498  891.016823 1509.726 1045980.3
4   1 2  67.50458  4556.8690 0.83843145 0.83714916  490.815893 1445.555  693993.5

but when I do write.matrix(moDat2, file = paste(targetPath, "dat2.csv", sep="/"), sep=",")

It save it to the file like this

p,q,s,S2,R2,R2adj,Cp,AIC,PRESS
0.000000e+00,1.000000e+00,1.672778e+02,2.798186e+04,          NA,          NA,3.679294e+03,          NA,          NA
1.000000e+00,2.000000e+00,1.603225e+02,2.570332e+04,8.866209e-02,8.142925e-02,3.343909e+03,1.666993e+03,3.338167e+06
1.000000e+00,2.000000e+00,8.673559e+01,7.523063e+03,7.332620e-01,7.311450e-01,8.910168e+02,1.509726e+03,1.045980e+06

Is there anyway I can save it to the file without the data getting transform to scientific notation?

Answer

Ricardo Saporta picture Ricardo Saporta · Dec 9, 2012

You can use format inside your write.matrix call.

  write.matrix(format(moDat2, scientific=FALSE), 
               file = paste(targetPath, "dat2.csv", sep="/"), sep=",")