R comparing two arrays

Viewed 741

I would like to compare two arrays. I need to test near equality among each elements . I am using all.equal(target, current , tolerance = ...), but it's probably wrong or maybe i didn't understand how all.equal works. I would like something with this behavior:

 a <-array(1:18, dim=c(3,3,2))
 b <- a
 b[3,3,2] <-18.01
 all.equal(a,b,tolerance = 0.1) # return TRUE
 all.equal(a,b,tolerance = 0.001) # return TRUE
 newFunction(a,b, tolerance = 0.1) # return TRUE
 newFunction(a,b, tolerance = 0.001) # return FALSE

Should i vectorized all.equal? Can you give me an hint please

1 Answers

I think the disconnect here is that the tolerance parameter doesn't do what you want. You're hoping that it will flag any individual differences that are greater than 0.001, but the all.equal() function works by considering the mean relative difference of the available entries. That is, it inherently compares everything in aggregate instead of looking elementy-by-element.

If you want an element-by-element comparison, you'll be better off just writing one directly, such as @Ben's comment of all(abs(a-b) < .001), or presumably whatever your newFunction() does.


To further flesh out the nuance of all.equal():

c <- a / 10
d <- c
d[3, 3, 2] <- 1.81
all.equal(c, d, tolerance = 0.1)   # returns TRUE
all.equal(c, d, tolerance = 0.001) # returns the mean relative difference

The difference in the last line with your corresponding line is that the mean relative difference now exceeds the tolerance of 0.001, even though the absolute differences between c and d are identical to those between a and b. Not only will all.equal() effectively consider all entries' differences simultaneously, but it will scale them to the sizes of the entries as well.

Related