[R] as.matrix does not turn data frame into character matrix

Jacob Wegelin jawegelin at ucdavis.edu
Fri Oct 17 02:23:41 CEST 2003


The as.matrix function behaves in a puzzling manner.  The help file says:
"`as.matrix' is a generic function. The method for data frames will
     convert any non-numeric column into a character vector using
     `format' and so return a character matrix."
But this does not appear to be the case in the following example. Instead,
as.matrix turns a data.frame into a list, not a character matrix, which
wreaks havoc with my old code.

junk<-
structure(list(SUBNUM = structure(c(3, 4, 5, 7, 6), class = "factor",
.Label = c("01",
"02", "03", "04", "07", "08", "09", "10", "11", "12", "13", "16",
"17", "18", "21", "22", "23", "24", "25", "26", "27", "28")),
    AGE = c(7, 7, 10, 8, 5), DIAGNOSI = c(1, 1, 1, 1, 1), cortrange =
structure(list(
        "03" = 19.0674, "04" = 40.3009, "07" = 37.0205, "09" = 8.84131,
        "08" = 10.9855), .Names = c("03", "04", "07", "09", "08"
    )), logcortrange = structure(list("03" = 1.90097866386896,
        "04" = 2.75040785570225, "07" = 3.15633470025647, "09" =
2.56744094585387,
        "08" = 2.84160608522206), .Names = c("03", "04", "07",
    "09", "08"))), .Names = c("SUBNUM", "AGE", "DIAGNOSI", "cortrange",
"logcortrange"), row.names = c("03", "04", "07", "09", "08"), class =
"data.frame")

> junk
   SUBNUM AGE DIAGNOSI cortrange logcortrange
03     03   7        1   19.0674     1.900979
04     04   7        1   40.3009     2.750408
07     07  10        1   37.0205     3.156335
09     09   8        1   8.84131     2.567441
08     08   5        1   10.9855     2.841606

> jank<-as.matrix(junk)
> jank
   SUBNUM AGE DIAGNOSI cortrange logcortrange
03 "03"   7   1        19.0674   1.900979
04 "04"   7   1        40.3009   2.750408
07 "07"   10  1        37.0205   3.156335
09 "09"   8   1        8.84131   2.567441
08 "08"   5   1        10.9855   2.841606

Notice that the first column is character, whereas the other columns are plain numeric!
This is *not* a matrix of character.

> dput(jank)
structure(list("03", "04", "07", "09", "08", 7, 7, 10, 8, 5,
    1, 1, 1, 1, 1, 19.0674, 40.3009, 37.0205, 8.84131, 10.9855,
    1.90097866386896, 2.75040785570225, 3.15633470025647, 2.56744094585387,
    2.84160608522206), .Dim = c(5, 5), .Dimnames = list(c("03",
"04", "07", "09", "08"), c("SUBNUM", "AGE", "DIAGNOSI", "cortrange",
"logcortrange")))

Is this a bug?

One result of this:

> cbind(dimnames(jank)[[1]], jank)
Error in cbind(...) : cannot create a matrix from these types

(I'm using version 7.0, because the links for downloading version 7.1 are dead today:)

> version
         _
platform i386-pc-mingw32
arch     i386
os       mingw32
system   i386, mingw32
status
major    1
minor    7.0
year     2003
month    04
day      16
language R

Thanks for any information.

Jake




More information about the R-help mailing list