[R] 0 * NA = NA

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


On 05-Mar-07 Petr Klasterecky wrote:
> Alberto Monteiro napsal(a):
>> 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. 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)
}

Ted.

> Petr
> 
>> 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
>> 
>> ______________________________________________
>> R-help at stat.math.ethz.ch mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>> 
> 
> -- 
> Petr Klasterecky
> Dept. of Probability and Statistics
> Charles University in Prague
> Czech Republic
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

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



More information about the R-help mailing list