Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove NA's when adding in R

Tags:

r

na

addition

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?

like image 815
random_forest_fanatic Avatar asked Mar 16 '26 04:03

random_forest_fanatic


1 Answers

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))

data

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)
like image 69
akrun Avatar answered Mar 19 '26 01:03

akrun