[R] 0 * NA = NA

(Ted Harding) ted.harding at nessie.mcc.ac.uk
Mon Mar 5 20:43:27 CET 2007


On 05-Mar-07 Alberto Monteiro wrote:
> 
> Of course, the problem begins to grow if we want, for example,
> to use elementary matrices to transform a matrix. The 2x2 matrix
> that switches two lines, rbind(c(0,1), c(1,0)) will not switch
> a matrix with NAs:
> 
> switch <- rbind(c(0,1), c(1,0))
> testmatrix <- rbind(c(1,2,3,4), c(5,6,7,8))
> switch %*% testmatrix # ok
> testmatrix[2,2] <- NA
> switch %*% testmatrix # not ok

Indeed! -- which is the sort of reason I said "This is a bit of a
tricky one, especially in a more general context."

There is no straightforward extension of my %*NA% operator which
deals with such a case, since the internal assignments

  X<-x;X[(is.na(x))&(y==0)]<-0;
  Y<-y;Y[(is.na(Y))&(x==0)]<-0;

fail because x (switch) and y (testmatrix) are non-conformable
(one being 2x2, the other 2x4).

Nor will it work if conformable, since then the 0's in switch
takes out the NA in the %*NA% operator:

testmatrix <- rbind(c(1,2), c(3,4))
testmatrix
     [,1] [,2]
[1,]    1    2
[2,]    3    4

switch %*NA% testmatrix
     [,1] [,2]
[1,]    3    4
[2,]    1    2 ## OK

testmatrix[2,2] <- NA
switch %*NA% testmatrix
     [,1] [,2]
[1,]    3    0
[2,]    1    2 ## Not OK!

So, if you want to simply multiply testmatrix by switch, with
terms 0*NA = 0, then you're OK; but you can't then use the same
operator for the purpose of switching rows, so you need a new
operator just for that kind of purpose.

Of course, for that specific purpose, index manipulation will
do the job:

  testmatrix
     [,1] [,2]
[1,]    1    2
[2,]    3   NA

  testmatrix[(2:1),]
     [,1] [,2]
[1,]    3   NA
[2,]    1    2

but it then disconnects it from the correspondence between
matrix multiplication and transformations.

Best wishes,
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 05-Mar-07                                       Time: 19:43:23
------------------------------ XFMail ------------------------------



More information about the R-help mailing list