[R] Annoyance in as.numeric

Bert Gunter gunter.berton at gene.com
Mon Jun 16 23:41:16 CEST 2008

On Mon, Jun 16, 2008 at  4:22 PM, Alberto Monteiro wrote:

> Why does as.numeric convert matrices and arrays to vectors?

Because that's what it's documented to do!

" as.numeric is a generic function, but S3 methods must be written for
as.double. It is identical to as.double (and as.real). "

And a check of the Help for as.double says:

"as.double attempts to coerce its argument to be of double type: like
as.vector it strips attributes including names. (To ensure that an object is
of double type without stripping attributes, use storage.mode)."

So, in particular, dim attributes of an array are stripped. To preserve
them,do what the Help tells you to:

> x <- matrix(c("1","2","3","4"),2,2)
> x
     [,1] [,2]
[1,] "1"  "3" 
[2,] "2"  "4" 
> storage.mode(x) <- "double"
> x
     [,1] [,2]
[1,]    1    3
[2,]    2    4


Bert Gunter
Genentech Nonclinical Statistics

More information about the R-help mailing list