JC3019
JC3019

Reputation: 383

identify if matrices have NAs in the same position (logical)

i want to identify whether two matrices have NA's in the same spot.

Setup: We have three matrices. I want to run a function that tells me mat1 and mat2 have NA's in identical spots, and that tells me that mat1(and mat3) vs mat2 have NA's in different spots

mat1 <- matrix(nrow=2, ncol =2, data =c(NA,0,0,NA))
mat2 <- matrix(nrow=2, ncol =2, data=c(NA,0,0,NA))
mat3 <- matrix(nrow=2, ncol=2, data = c(NA,0,0,0))

Upvotes: 1

Views: 117

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389145

We can write a function which compares the position of NA elements in two matrix

identical_NA_matrix <- function(m1, m2) {
   identical(which(is.na(m1), arr.ind = TRUE), which(is.na(m2), arr.ind = TRUE))
}

identical_NA_matrix(mat1,mat3)
#[1] FALSE
identical_NA_matrix(mat1,mat2)
#[1] TRUE

Upvotes: 2

Spacedman
Spacedman

Reputation: 94237

Compare the NA status of all elements:

> all(is.na(mat1) == is.na(mat2))
[1] TRUE
> all(is.na(mat1) == is.na(mat3))
[1] FALSE

In a function I'd do this:

> nanana = function(m1, m2){!any(is.na(m1) != is.na(m2))}

I've inverted the logic so that any can stop checking if it finds any difference. If you use all it has to go over every element. I'm not sure if this kind of short-circuiting is in R but it might save you a millisecond or two.

> nanana(mat1, mat2)
[1] TRUE
> nanana(mat1, mat3)
[1] FALSE

Upvotes: 5

Related Questions