[R] 0 * NA = NA

Alberto Monteiro albmont at centroin.com.br
Mon Mar 5 18:22:43 CET 2007


Ted Harding wrote:
>
>>> Is there any way to "force" 0 * NA to be 0 instead of NA?
>> 
>> No (AFAIK), and it is pretty reasonable to define it this way.
>> If you want to treat the NAs as zeros, use
>> x[is.na(x)] <- 0
> 
> Doing it in precisely that way would have the problem that it
> would not give you NA when it should. For example:
> 
> x <- c(1, NA, 1)
> wt <- c(2, 1, 1)
> 
> Then, after x[is.na(x)] <- 0, the result of x %*% wt should be NA,
> but your method would give 3.
>
That's precisely my thought - since you may have read my thoughts,
it's time to recalibrate my alluminium helmet.

But I also thought about something else. What is the meaning of NA? 
NA is a _missing_ value, and is.infinite(NA) returns FALSE [OTOH, 
is.finite(NA) returns FALSE too - this is weird]. A missing value
times zero is zero. OTOH, 1/NA is NA, so NA could mean Inf.

Maybe binary logic can't adequately handle such ideas :-/

if (NA == 0) is NA, then is.finite(NA) should be NA too...

if (NA == 0) 2 else 3 # gives an error

> This is why I suggested a method
> which tests for corresponding elements of x = NA and y = 0, since
> what Alberto Monteiro wanted was 0*NA = 0, when that combination
> occures. I.e.
> 
> "%*NA%" <- function(x,y){
>   X<-x;X[(is.na(x))&(y==0)]<-0;
>   Y<-y;Y[(is.na(y))&(x==0)]<-0;
>   return(X%*%Y)
> }
> 
This method is fine. I had already done something similar

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

But I digress...

Alberto Monteiro



More information about the R-help mailing list