Reputation: 1252
I'm trying to add two matrices in R, and I'd like the addition to treat any NA's as 0's. I know I could always do something like this:
ifelse(is.na(A), 0, A) + ifelse(is.na(B), 0, B)
but it seems like there should be a more elegant way of doing this. For example, is there some way of supplying the na.rm argument to the + function?
Upvotes: 3
Views: 1253
Reputation: 887088
Assuming that "A" and "B" have the same dimensions,
`dim<-`(colSums(rbind(c(A), c(B)), na.rm=TRUE), dim(A))
# [,1] [,2] [,3] [,4]
#[1,] 4 7 6 6
#[2,] 5 7 2 4
#[3,] 8 9 6 1
#[4,] 4 2 5 5
Or instead of ifelse
, we could use replace
which will be a bit faster
replace(A, is.na(A), 0) +replace(B, is.na(B), 0)
# [,1] [,2] [,3] [,4]
#[1,] 4 7 6 6
#[2,] 5 7 2 4
#[3,] 8 9 6 1
#[4,] 4 2 5 5
Or if there are multiple datasets, we can place it in a list and work with Reduce
Reduce(`+`, lapply(list(A,B), function(x) replace(x, is.na(x), 0)))
Another compact option would be to use NAer
from qdap
library(qdap)
NAer(A)+NAer(B)
For multiple datasets
Reduce(`+`, lapply(list(A,B), NAer))
set.seed(324)
A <- matrix(sample(c(NA,1:5), 4*4, replace=TRUE), ncol=4)
set.seed(59)
B <- matrix(sample(c(NA,1:5), 4*4, replace=TRUE), ncol=4)
Upvotes: 4
Reputation: 99331
You can try recode
from the car
package
A <- matrix(c(1,NA,5,9,3,NA), 2)
B <- matrix(c(NA,10,3,NA,21,3), 2)
library(car)
Reduce("+", lapply(list(A, B), recode, "NA=0"))
# [,1] [,2] [,3]
# [1,] 1 8 24
# [2,] 10 9 3
Upvotes: 3