I want to calculate the sum over matrices and ignore any NAs contained, as in the following example:
x1 <- matrix(c(NA,NA,2,2),2,2)
x2 <- matrix(c(NA,3,NA,NA),2,2)
x3 <- matrix(c(NA,NA,NA,NA),2,2)
x4 <- matrix(c(1,2,3,4),2,2)
lx <- list(x1,x2,x3,x4)
Reduce('+',lx) # does not work because of NAs
result <- matrix(c(1,5,5,6),2,2)
So the result should be:
[,1] [,2]
[1,] 1 5
[2,] 5 6
How can this be done?
We can write a custom function and use it in Reduce
. We replace the NA
s with 0's and then we add them.
modifiedSum <- function(x, y) {
replace(x, is.na(x), 0) + replace(y, is.na(y), 0)
}
Reduce(modifiedSum, lx)
# [,1] [,2]
#[1,] 1 5
#[2,] 5 6