[R] Matrix subsetting {was "... vectorized nested loop..."}

Martin Maechler maechler at stat.math.ethz.ch
Wed Jan 24 11:57:48 CET 2007


Hi Jose,
I'm answering your second batch of questions, since
Chuck Berry has already well done so with the first one

>>>>> "Jose" == Jose Quesada <quesada at gmail.com>
>>>>>     on Tue, 23 Jan 2007 21:46:27 +0100 writes:

[........]

    Jose> # example
    Jose> library(Matrix)
    Jose> x = as(x,"CsparseMatrix")

[..........]

    Jose> Also, I have noticed that getting a row from a Matrix
    Jose> object produces a normal array (i.e., it does not
    Jose> inherit Matrix class). 

This is very much on purpose, following the principle of "least
surprise" so I'm surprised you're suprised.. :

The 'Matrix' behavior has been modelled to follow the more than
20 years old 'matrix' behavior :

 > matrix(1:9, 3) [,2]
 [1] 4 5 6
 > matrix(1:9, 3) [,2 , drop=FALSE]
      [,1]
 [1,]    4
 [2,]    5
 [3,]    6
 > library(Matrix)
 Loading required package: lattice
 > Matrix(1:9, 3) [,2]
 [1] 4 5 6
 > Matrix(1:9, 3) [,2, drop = FALSE]
 3 x 1 Matrix of class "dgeMatrix"
      [,1]
 [1,]    4
 [2,]    5
 [3,]    6
 > 

But then I should not be surprised, because
there has been the R FAQ

>> 7.5 Why do my matrices lose dimensions?

for quite a while.

*And* I think that there is only one "thing" in the S language
about which every "knowledgable one" agrees that it's a "design
bug", and that's the fact that 'drop = TRUE' is the default, and
not 'drop = FALSE' {but it's not possible to change now, please
don't start that discussion!}

    
Given what I say above, I wonder if our ("new-style") 'Matrix'
objects should not behave differently than ("old-style") 'matrix' and
indeed do use a default 'drop = FALSE'.
This might break some Matrix-based code though, but then
'Matrix' is young enough, and working Matrix indexing is much
younger,  and there are only about 4 CRAN/Bioconductor
packages depending on 'Matrix'.
--> This discussion (about changing this behavior in the
"Matrix" package) should definitely be lead on the R-devel
mailing list --> CC'ing to R-devel
{hence one (but please *only* one !) cross-post}

    Jose> However, selecting >1 rows,
    Jose> does produce a same-class matrix. If I convert with
    Jose> as() the output of selecting one row, am I losing
    Jose> performance? Is there any way to make the resulting
    Jose> vector be a 1-D Matrix object?

yes, ", drop = FALSE", see above

Martin



More information about the R-help mailing list