[R] Vectorial analogue of all.equal()?
Rui Barradas
ruipbarradas at sapo.pt
Sat Sep 1 16:20:26 CEST 2012
Hello,
Like this?
equals <- function(x, y, tol = .Machine$double.eps^0.5) abs(x - y) < tol
x <- rnorm(5)
y <- x[2]
equals(x, y)
[1] FALSE TRUE FALSE FALSE FALSE
y <- rnorm(3)
y[2] <- x[2]
equals(x, y)
[1] FALSE TRUE FALSE FALSE FALSE
Warning message:
In x - y : longer object length is not a multiple of shorter object length
Hope this helps,
Rui Barradas
Em 01-09-2012 14:48, (Ted Harding) escreveu:
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list