Reputation: 613
I have two datasets, and I want to know at which location their elements are different, so I use the code below:
In this example, a1 and a2 are the datasets to be compared. The "a2" has two differnt elements: one is [3,1], the other is [8,2] which is "NA".
a1 <- data.frame(num = 1:8, lib = letters[1:8])
a2 <- a1
a2[[3,1]] <- 2
a2[[8,2]] <- 2
a1; a2
which(a1 != a2, arr.ind = TRUE)
However, the which() function only finds one difference "[3,1]". It seems that it cannot find the "NA" difference. How can I find both [3,1] and [8,2] differences?
Upvotes: 2
Views: 98
Reputation: 389047
That is because when anything compared to NA
is NA
, it doesn't return TRUE
or FALSE
hence it is not captured in which
"h" != NA
#[1] NA
We might need an additional check for NA
elements
which((a1 != a2) | (is.na(a1) != is.na(a2)), arr.ind = TRUE)
# row col
#[1,] 3 1
#[2,] 8 2
Upvotes: 12