[R] 0 * NA = NA

(Ted Harding) ted.harding at nessie.mcc.ac.uk
Mon Mar 5 16:07:35 CET 2007


On 05-Mar-07 Alberto Monteiro wrote:
> Is there any way to "force" 0 * NA to be 0 instead of NA?
> 
> For example, suppose I have a vector with some valid values, while
> other values are NA. If I matrix-pre-multiply this by a weight 
> row vector, whose weights that correspond to the NAs are zero,
> the outcome will still be NA:
> 
> x <- c(1, NA, 1)
> wt <- c(2, 0, 1)
> wt %*% x # NA
> 
> Alberto Monteiro

This is a bit of a tricky one, especially in a more general context.
I think it involves defining new operators.

In the case of the particular operation in your example, you could do

"%*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)
}

Then:

  x <- c(1, NA, 1)
  wt <- c(2, 0, 1)

  x %*NA% wt
       [,1]
  [1,]    3


Hmmm!
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 05-Mar-07                                       Time: 15:07:19
------------------------------ XFMail ------------------------------



More information about the R-help mailing list