[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 12:50:03 CEST 2014


> > Is there an easy way to check whether a variable is within  +/- 10%
> > range of another variable in R?

You could use
2*abs(A-B)/(A+B) < 0.1

which avoids an apply().
I've assumed you meant different by under 10% of the mean of the two, hence the 2/(A+B); if you meant 10% of something else, same kind of thing should work with a different bottom line. For example if you meant less than 10% of the smaller of the two, abs(A-B)/pmin(A, B) < 0.1 would do that

And if you want to check that  they all comply,
all( 2*abs(A-B)/(A+B) < 0.1 )

will do that.

I liked Peter Langfelder's suggestion of all.equal, though;  an interesting use of a tolerance I've previously seen as there only to compensate for floating point representation errors. 

Steve E




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



More information about the R-help mailing list