[R] How to check to see if a variable is within a range of another variable

S Ellison S.Ellison at LGCGroup.com
Thu Oct 2 15:55:11 CEST 2014


Keith Jewell said:
> ... from reading ?all.equal I would have expected
> scale = 1 and the default scale = NULL to give identical results for the length
> one numerics being passed to all.equal.
> 
> Can anyone explain?

Inspectng the code in all.equal.numeric, I find

xy <- mean((if (cplx) 
        Mod
    else abs)(target - current))
if (is.null(scale)) {
        xn <- mean(abs(target))
        if (is.finite(xn) && xn > tolerance) {
            xy <- xy/xn
            "relative"
        }
        else "absolute"
    }
    else {
        xy <- xy/scale
        if (scale == 1) 
            "absolute"
        else "scaled"
    }

target is the first number supplied, current the second; in yoour example code that is x[2] and x[1] respectively. Later on xy is compared to the tolerance.

In the code, scale=NULL and scale=1 are clearly treated differently; in particular when scale is NULL the absolute difference is divided by first of the (two) numbers if that number is greater than tolerance or is used unchanged, and if scale=1 it is divided by scale throughout.

That would mean that for scale=NULL, your example will divide the difference by 10, 9, ..1 in that order before comparing with tolerance, and if scale=1 it will simply compare the difference directly with the tolerance. Calculating your case through for scale = NULL, xy will take the values 
ifelse(b>5, abs(a-b)/b, abs(a-b))
 [1] 0.9000000 0.7777778 0.6250000 0.4285714 0.1666667 1.0000000 3.0000000
 [8] 5.0000000 7.0000000 9.0000000

Of those, only the last 2 are greater than 5, which is the result you found. By contrast, when scale=1 xy takes the values
abs(a-b)
  [1] 9 7 5 3 1 1 3 5 7 9
of which the two at each end are both greater than 5.

That fairly complicated behavio0ur is probably a good reason to use a simpler calculation in which you can see how the difference is being scaled ... ;)

Steve Ellison


 


*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}



More information about the R-help mailing list