[R] Subsetting a matrix
Adelchi Azzalini
azzalini at stat.unipd.it
Mon Jul 14 12:24:36 CEST 2003
On Monday 14 July 2003 11:59, you wrote:
> I'd welcome some comments or advice regarding the situation described
> below.
>
> The following illustrates what seems to me to be an inconsistency
> in the behaviour of matrix subsetting:
>
> > Z<-matrix(c(1.1,2.1,3.1,1.2,2.2,3.2,1.3,2.3,3.3),nrow=3)
> > Z
> [,1] [,2] [,3]
> [1,] 1.1 1.2 1.3
> [2,] 2.1 2.2 2.3
> [3,] 3.1 3.2 3.3
> > dim(Z)
> [1] 3 3
>
> > Z0<-Z[c(T,F,F),c(F,T,T)]
> > Z0
> [1] 1.2 1.3
> > dim(Z0)
> NULL
>
> whereas, of course, with
>
> > Z1<-Z[c(T,T,F),c(F,T,T)]
> > Z1
> [,1] [,2]
> [1,] 1.2 1.3
> [2,] 2.2 2.3
> > dim(Z1)
> [1] 2 2
>
> i.e. a fully-paid-up matrix.
>
> What I would have expected is that Z0 should come out as a 1x2 matrix:
>
> [,1] [,2]
> [1,] 1.2 1.3
>
> with dim(Z0) --> [1] 1 2
This seems to me yet another example of the side-effects caused by
the automatic conversion of matrix to "vector" (in Splus/R sense)
when the one of the dimension is 1. There are many examples of this
sort.
Of course the remedy is to do
Z0 <- Z[c(T,F,F),c(F,T,T), drop=FALSE]
Personally, I find this automatic conversion to "vector" a somewhat confusing
feature (although I can see its reasons), and I know of many people that would
have preferred that drop=FALSE was the default behaviour, but surely now
is difficult to change it.
regards
Adelchi Azzalini
--
Adelchi Azzalini <azzalini at stat.unipd.it>
Dipart.Scienze Statistiche, Università di Padova, Italia
http://azzalini.stat.unipd.it/
More information about the R-help
mailing list