[Rd] Re: matrix subsetting (was: [R] as(obj,"matrix"))

From: Patrick Burns <pburns_at_pburns.seanet.com>
Date: Fri 30 Jul 2004 - 06:46:27 EST

On a related topic, a client came up with this example a few days ago which I was unable to explain. (But he did heed my advise of "don't do that".)

 > matrixObj <- array(1:4, c(2,2))
 > class(matrixObj) <- "matrix"
 > fooObj <- matrixObj
 > class(fooObj) <- "foo"
 > fooObj[1:2]
Testing
     [,1] [,2]

[1,] 1 3
[2,] 2 4
attr(,"class")
[1] "foo"
 > matrixObj[1:2]
[1] 1 2
 > get("[.matrix")
function(x, i, j, drop = if(missing(i)) TRUE else length(cols)==1) {

    cat("Testing\n")
    x
}
 > get("[.foo")
function(x, i, j, drop = if(missing(i)) TRUE else length(cols)==1) {

    cat("Testing\n")
    x
}

Everything is the same except for the name of the class. When the class is "matrix", it ignores the subset method. But the very same code works if the class is "foo". This is 1.9.1 Windows, and the same happens with 1.7.0 (the oldest version I have on my machine).

What is happening here?

Patrick Burns

Burns Statistics
patrick@burns-stat.com
+44 (0)20 8525 0696
http://www.burns-stat.com
(home of S Poetry and "A Guide for the Unwilling S User")

John Chambers wrote:

>Wolski wrote:
>
>
>>Hi!
>>
>>Here a simple example.
>>
>>setClass("myclass"
>>,representation(info="character")
>>,contains="matrix"
>>)
>>
>>rownames(dd)<-c("a","b")
>>tt<-new("myclass",dd)
>>#the source of pain.
>>as(tt,"matrix")<-matrix(1,3,3)
>>Error: length of dimnames [1] not equal to array extent
>>
>>Is there a different way to do what I would like to do (I would like to change the @.Data and all its attributes in the object)?
>>
>>
>
>It's not particularly a problem with as(). Your class just doesn't
>behave as you expect.
>
>"matrix" is not a formal class with slots. (It isn't even an S3 class
>in R; attr(x,"class") is NULL.) So you cannot expect classes extending
>"matrix" to know what a matrix is supposed to be.
>
>Part of the problem is that matrix objects sometimes have dimnames and
>sometimes don't. And there is basic code in R that assumes or applies
>constraints on the "dim" or "dimnames".
>
>In S-Plus, "matrix" is a formal class, always having a slot for
>dimnames. R has not gone that route, at least not yet.
>
>It may be possible to define a new class, "Matrix", say, that looks like
>a matrix to old-style code but has a formal definition. But the details
>are likely to be tricky, and it's definitely a topic for r-devel, not
>r-help.
>
>John Chambers
>
>
>
>>Eryk.
>>
>>______________________________________________
>>R-help@stat.math.ethz.ch mailing list
>>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>>
>>
>
>
>



R-devel@stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-devel Received on Fri Jul 30 06:54:47 2004

This archive was generated by hypermail 2.1.8 : Fri 18 Mar 2005 - 08:59:15 EST