[R] peculiar matrices

Marc Schwartz (via MN) mschwartz at mn.rr.com
Fri Oct 21 23:56:18 CEST 2005


On Fri, 2005-10-21 at 21:32 +0000, Ben Bolker wrote:
> As far as I can tell from reading The Fine Documentation
> (R Language Definition and Intro to R), matrices are supposed
> to be of homogeneous types.  Yet giving matrix() an inhomogeneous
> list seems to work, although it produces a peculiar object:
> 
> v = list(1:3,4,5,"a")
> m = matrix(v,nrow=2)
> m
> 
>      [,1]      [,2]
> [1,] Integer,3 5
> [2,] 4         "a"
> 
> 
> m[1,]
> 
> [[1]]
> [1] 1 2 3
> 
> [[2]]
> [1] 3
> 
>  (this is R 2.1.1, running under Linux)

Ben,

If you review the structure of 'm' note:

> str(m)
List of 4
 $ : int [1:3] 1 2 3
 $ : num 4
 $ : num 5
 $ : chr "a"
 - attr(*, "dim")= int [1:2] 2 2

that it is actually a list, even though:

> class(m)
[1] "matrix"


Also:

> mode(m)
[1] "list"

> typeof(m)
[1] "list"


If you remove the dim attributes, you get:

> dim(m) <- NULL
> m
[[1]]
[1] 1 2 3

[[2]]
[1] 4

[[3]]
[1] 5

[[4]]
[1] "a"


So I would argue that it is consistent with the documentation in that,
while the printed output is that of a matrix, it is a list, which of
course can handle heterogeneous data types.

This is Version 2.2.0 Patched (2005-10-20 r35979).


>   Should there be a check/error? Or is this just analogous to
> the joke about going to the doctor and saying "it hurts when
> I do this", and the doctor saying "well then, don't do that"?


Maybe more like:

"Doctor, my eye hurts when I drink my tea." and the doctor says, "Well,
remove the spoon from the cup before you drink."

;-)

Regards,

Marc Schwartz




More information about the R-help mailing list