[R] How to convert character matrix or data.frame to numeric?

hadley wickham h.wickham at gmail.com
Mon Jan 18 20:46:37 CET 2010


> Ouch!   Hmmm.   From the "Value" section of the apply docs... "If each call
> to FUN returns a vector of length n, then apply returns an array of
> dimension c(n, dim(X)[MARGIN]) if n > 1."  Since I set MARGIN to 1, then I
> was operating on rows where n  is 3.
>
>> c(n, dim(X)[MARGIN])
> [1] 3 2
>
> How about that; it does just what it says it will do.  I have no idea why it
> does that, but the remedy seems to be ...
>
>> apply(X, c(1,2), as.numeric)
>     [,1] [,2] [,3]
> [1,]    1    3    5
> [2,]    2    4    6
>
> ... or even ...
>
>> apply(X, 2, as.numeric)
>     [,1] [,2] [,3]
> [1,]    1    3    5
> [2,]    2    4    6
>
> Perhaps someone could shed light on why the rows become columns.

I've never understood why that happens either.  That's why aaply in
the plyr package preserves the existing dimension structure as much as
possible.

Hadley

-- 
http://had.co.nz/



More information about the R-help mailing list