# [R] add/subtract matrices, ignoring NA or missing values

Gabor Grothendieck ggrothendieck at gmail.com
Tue Jan 29 04:09:25 CET 2008

```Perhaps you could explain the motivation behind this.  At any rate here
are three different solutions:

ifelse(is.na(m1), ifelse(is.na(m2), NA, m2), ifelse(is.na(m2), m1, m1 + m2))

apply(array(c(m1, m2), c(2,2,2)), 1:2, function(x) sum(c(na.omit(x), NA)[1]))

na.m1 <- is.na(m1)
na.m2 <- is.na(m2)
ifelse(na.m1 & na.m2, NA, ifelse(na.m1, 0, m1) + ifelse(na.m2, 0, m2))

On Jan 28, 2008 9:34 PM, Ng Stanley <stanleyngkl at gmail.com> wrote:
> Hi,
>
> For example, given two 2x2 matrices m1 and m2. I would like to add/subtract
> element by element
>
> > m1
>         [,1] [,2]
> [1,]   NA   NA
> [2,]    1    2
>
> > m2
>        [,1] [,2]
> [1,]    1   NA
> [2,]   NA    2
>
> > m1 + m2
>        [,1] [,2]
> [1,]   NA   NA
> [2,]   NA    4
>
> How can I ignore the NA, and get this ? Hope the solution can be extended to
> subtract and modulo also.
>
>        [,1] [,2]
> [1,]   1   NA
> [2,]   1    4
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help