Skip to content

problem with all/all.equal

6 messages · Laura Smith, Peter Langfelder, Brad Patrick Schneid +3 more

#
On Wed, Apr 6, 2011 at 3:09 PM, Laura Smith <smithlaura937 at gmail.com> wrote:
all looks at a logical vector (or two), and all.equal compares two
objects. For your purposes, you can ask whether

all (x==x[1])

for example.

Peter
#
Hi Laura,

You have gotten several good suggestions.  Here are two more that may
be helpful if you have (or potentially could have) unruly data.  In
one case, the values are theoretically, but not computationally
identical.  In the other, missing values lead to NA being returned,
which may be a problem if you are using the logical test with an if()
statement.

### Two pathologic examples ###
# One: the floating point problem
all((x <- c(1 - .4, .4 + .2)) == x[1])
ifelse(length(unique(x))==1, "All Equal", "Not All Equal")
print(x, digits = 22)
## another option
tol <- .Machine$double.eps^0.5 # standard tolerance
all(x < x[1] + tol | x > x[1] - tol)
# Two: the missing problem
x <- c(NA, NA)
all(x < x[1] + tol | x > x[1] - tol)
## another option
isTRUE(all(x < x[1] + tol | x > x[1] - tol))

Best Regards,

Josh
On Wed, Apr 6, 2011 at 3:09 PM, Laura Smith <smithlaura937 at gmail.com> wrote:

  
    
#
On Wed, Apr 6, 2011 at 9:23 PM, Joshua Wiley <jwiley.psych at gmail.com> wrote:
or briefer

all(abs(x-x[1]) < tol)

or, by first doing library("R.utils"),

all(isZero(x-x[1]))
or

all(x < x[1] + tol | x > x[1] - tol, na.rm=TRUE)

or

all(isZero(x-x[1]), na.rm=TRUE)

My $.02

/Henrik
6 days later
#
The help pages for identical() and all.equal() have information that will
make it clear why they don't do what you want.

In the meantime, I tend to use a construct such as:

   length(unique(x))==1

But be careful if x is not a vector.
No doubt there are other ways.

-Don