[R] Subsetting a matrix
(Ted Harding)
Ted.Harding at nessie.mcc.ac.uk
Mon Jul 14 11:59:04 CEST 2003
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
but it does not -- it does not have matrix status. I know it will try
to behave politely if forced into matrix-algebra society, but it betrays
its lack of true poise in solecisms like the following:
> Z0%*%Z1[1:2,1]
[,1]
[1,] 4.3
> Z1[1:2,1]%*%Z0
[,1]
[1,] 4.3
One of these should be a scalar (in fact the first, given how Z0 was
created), and the other a 2x2 matrix. Z0 simply does not know that you
have to behave differently if seated on someone's right rather than
on their left.
Now of course one can send Z0 away for remedial training ( t() ):
> Z0<-t(Z0)
> Z0
[,1] [,2]
[1,] 1.2 1.3
> Z0%*%Z1[1:2,1]
[,1]
[1,] 4.3
> Z1[1:2,1]%*%Z0
[,1] [,2]
[1,] 1.44 1.56
[2,] 2.64 2.86
and now it does know how to behave. But it would save some bother (and
having to worry about this sort of thing in the midst of complex matrix
algebra) if matrix subsetting worked in a consistent way for all possible
subsets including cases which should result in 1xk or kx1 matrices
(where, by the way, we could have k=1 and get a 1x1 matrix).
Is there perhaps some global option which regulates this sort of
behaviour? Or is the underclass always with us?
With thanks,
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 167 1972
Date: 14-Jul-03 Time: 10:59:04
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list