[R] Converting the columns of a data frame to numeric

Uwe Ligges ligges at statistik.uni-dortmund.de
Sun Sep 1 22:18:32 CEST 2002


Daniel Mastropietro wrote:
> 
> Hello,
> 
> I have a data frame whose columns are factors with numeric levels and I
> want to convert the columns to numeric so that I can treat the data frame
> as a matrix.
> I found a way of doing this but would like to know if there is an easier way.
> 
> My way is:
> 
> M <- matrix(ncol=ncol(df) , nrow=nrow(df) , as.numeric(as.matrix(df)))
> 
> where 'df' is the data frame.
> 
> I am wondering if there is a function, similar to as.numeric(), that
> converts each column of the matrix 'as.matrix(df)' to numeric.

In your case
  apply(df, 2, as.numeric)
should work (coercing each column to numeric and the data.frame to a
matrix). 
Since it operates on vectors and not on the whole object, this way is
less efficient than the way you mentioned above. 

If you import the data.frame, you might want to tell R that the column
should be treated as numeric.

Uwe Ligges
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list