ana_gg
ana_gg

Reputation: 370

NA + 0 = 0, NA + 1 = 1, NA + NA = NA in R

I have a dataframe with some NAs as follows:

set.seed(1)
M<-matrix(sample(0:1,100,replace=TRUE),ncol=10)
M <- as.data.frame(M)
M[3,1]<-NA
M[10,5]<-NA
M[10,6]<-NA
M[8,10]<-NA

I want to sum every two columns as follows: M_final = M[c(TRUE,FALSE)]+M[c(FALSE,TRUE)]

But I want to have NA in the M_final only when two NAs are added. So I expect the output to be:

   V1 V3 V5 V7 V9
1   0  1  2  1  1
2   1  1  1  2  1
3   0  0  1  1  1
4   0  1  2  1  1
5   1  0  1  1  0
6   1  0  1  2  1
7   1  2  2  2  0
8   1  0  2  0  1
9   2  1  1  1  1
10  1  2 NA  2  1

Any ideas?? Thanks!!

Upvotes: 0

Views: 61

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388972

You can write a custom function to handle this.

add_NA <- function(x, y) ifelse(is.na(x) & is.na(y), NA, rowSums(cbind(x, y), na.rm = TRUE))

Use mapply to apply them in pairs

mapply(add_NA, M[c(TRUE,FALSE)], M[c(FALSE,TRUE)])

#.     V1 V3 V5 V7 V9
# [1,]  0  1  2  1  1
# [2,]  1  1  1  2  1
# [3,]  0  0  1  1  1
# [4,]  0  1  2  1  1
# [5,]  1  0  1  1  0
# [6,]  1  0  1  2  1
# [7,]  1  2  2  2  0
# [8,]  1  0  2  0  1
# [9,]  2  1  1  1  1
#[10,]  1  2 NA  2  1

Upvotes: 3

Related Questions