Skip to content

How to convert character matrix or data.frame to numeric?

2 messages · Ben Tupper, Hadley Wickham

#
Hello again,
On Jan 17, 2010, at 5:42 PM, Rolf Turner wrote:

            
Whoa!   Let's try that again, but with a better example.

 > X = matrix(as.character(1:6),2,3)
 > X
      [,1] [,2] [,3]
[1,] "1"  "3"  "5"
[2,] "2"  "4"  "6"
 > apply(X,1,as.numeric)
      [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6

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.

Cheers,
Ben
Cheers,
Ben
#
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