Search code examples
rnacross-product

How to handle missing values in crossprod in R?


I am trying to calculate the sum products of two vectors, but there is NA in one of them.

crossprod(c(4.5,4,4,3,NA), c(1,5,4,1,1))

In calculating, I want to treat NA as a zero. But in original data frame,I still want to keep it as NA for further data processing. Any hint will be appreciated.


Solution

  • If your cross product is more complex than a sum, you can define a new function which replaces NA in the arguments:

    crossprod.replacena <- function(x, y, val=0) {
                                      crossprod(replace(x, is.na(x), val), 
                                                replace(y, is.na(y), val)
                                      )
                            }
    

    Or you can call replace on your arguments without defining a function, as replace does not modify its arguments.