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]]
Rolf Turner
2008-Jan-29 02:58 UTC
[R] add/subtract matrices, ignoring NA or missing values
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 4In 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}}
Gabor Grothendieck
2008-Jan-29 03:09 UTC
[R] add/subtract matrices, ignoring NA or missing values
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 > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >