[R] help with element-by-element sum with NA

Peter Ehlers ehlers at ucalgary.ca
Wed Jul 25 01:54:40 CEST 2012


On 2012-07-23 21:48, R. Michael Weylandt wrote:
> Perhaps something like:
>
> Reduce(function(x,y){x[is.na(x)] <- 0; y[is.na(y)] <- 0; x + y}, list(A,B,C))
>
> Not the most elegant, but it will get the job done.
>
> Michael

I like Reduce(), but here are a couple more solutions:

1.
   tmp <- mapply(FUN = sum, A, B, C,
                 MoreArgs = list(na.rm = TRUE))
   matrix(tmp, nrow(A))

2.
Using the abind package to create a 3D array and
then using apply() to sum over the appropriate
columns in the array:

   require(abind)
   tmp <- abind(A, B, C, along = ncol(A) + 1)
   apply(tmp, 1:2, sum, na.rm = TRUE)

2a.
Both of the above solutions generate zeros where
one might prefer NA. Here's a way to get the NAs:

   sum2 <- function(x){
     ifelse(all(is.na(x)), NA, sum(x, na.rm = TRUE))
   }
   apply(tmp, 1:2, sum2)

Peter Ehlers

>
> On Mon, Jul 23, 2012 at 3:47 PM, Thiago Couto <couto.thiagoba at gmail.com> wrote:
>> Hi,
>>
>>      I have three matrices which could be, for example:
>>      A =  0, NA
>>             NA, 3
>>
>>      B =  1, NA
>>              0, NA
>>
>>      C = 1, NA
>>              1, 1
>>
>>      (The point is that they all may have NA's in some cells)
>>
>>      QUESTION: How do I perform a element-by-element sum of the elements of
>>      these three matrices (A + B + C), ignoring NA's, to obtain:
>>
>>      D = 2, NA
>>             1, 4
>>
>>      In reality I am handling much larger matrices (not just 2x2).
>>
>>      Thank you for any help!
>>
>>          [[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.
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list