[R] Vectorial analogue of all.equal()?

(Ted Harding) Ted.Harding at wlandres.net
Sat Sep 1 15:48:06 CEST 2012


Greetings All.

Once again, I am probably missing something fairly accessible,
but since I can't find it I'd welcome advice!

I have a dataframe derived from a text file of data in tabular
format. For one of the variables, say X, I want to select the
subsets which in which X equals a particular value.

Such values are given in the text file like: 2.3978953, and each
such value will occurr several times. So, for example, I want
to select that subset of rows for which X "equals" 2.3978953 .

However, "==" of course will not do, because it is intolerant of
rounding errors. Nor will all.equal(), which does have tolerance,
since it only returns a single TRUE/FALSE (and in any case will
not compare a vector with a value. But the only guidance I can
find for this situation, using ?"==", says:

  For numerical and complex values, remember '==' and ?!=? do not
  allow for the finite representation of fractions, nor for rounding
  error. Using 'all.equal with 'identical is almost always preferable.
  See the examples.

But the only relevant example is:

  x1 <- 0.5 - 0.3
  x2 <- 0.3 - 0.1
  x1 == x2                           # FALSE on most machines
  identical(all.equal(x1, x2), TRUE) # TRUE everywhere

which is not a vectorial example.

I do have a work-round of the form:

  ix <- which(round(X,4)==round(2.3978953,4))

(where rounding to 4 decimal places is enough to distinguish X-values).

As said above,

  ix <- which(X==2.3978953)

will not do, since 'which(X==x)' returns an empty result. And using
all.equal(X,2.3978953) fails because X and 2.3978953 are of unequal
lengths.

So it would be nice if there were a function (which I can of course
define for myself), say equals(), such that

  equals(X,2.3978953)

(with optional "tol=" argument) would test for equality to within
tolerance, and return a vector of TRUE/FALSE according to the values
in X.

Or, indeed, perhaps I am overlooking something.

Ted.

-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 01-Sep-2012  Time: 14:48:01
This message was sent by XFMail



More information about the R-help mailing list