[R] add/subtract matrices, ignoring NA or missing values
Rolf Turner
r.turner at auckland.ac.nz
Tue Jan 29 03:58:19 CET 2008
On 29/01/2008, at 3:34 PM, Ng Stanley 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
In a word ***DON'T***. A missing value is missing. It is not the
same as zero!
If it really should be zero it would've been coded as zero to start
with.
It appears from your example that you want NAs to be treated as being
zero, except
when you are adding two of them, in which case you want the sum to be
NA. I may
be suffering from poverty of imagination, but I cannot imagine a
situation in which
this would be a sensible thing to do.
I could easily give you code to arrange for what you want to happen,
but I'm not going
to, since I do not wish to encourage misguided behaviour.
cheers,
Rolf Turner
######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}
More information about the R-help
mailing list