Test for equality among all elements of a single numeric vector Test for equality among all elements of a single numeric vector r r

Test for equality among all elements of a single numeric vector


Why not simply using the variance:

var(x) == 0

If all the elements of x are equal, you will get a variance of 0.


If they're all numeric values then if tol is your tolerance then...

all( abs(y - mean(y)) < tol ) 

is the solution to your problem.

EDIT:

After looking at this, and other answers, and benchmarking a few things the following comes out over twice as fast as the DWin answer.

abs(max(x) - min(x)) < tol

This is a bit surprisingly faster than diff(range(x)) since diff shouldn't be much different than - and abs with two numbers. Requesting the range should optimize getting the minimum and maximum. Both diff and range are primitive functions. But the timing doesn't lie.


I use this method, which compares the min and the max, after dividing by the mean:

# Determine if range of vector is FP 0.zero_range <- function(x, tol = .Machine$double.eps ^ 0.5) {  if (length(x) == 1) return(TRUE)  x <- range(x) / mean(x)  isTRUE(all.equal(x[1], x[2], tolerance = tol))}

If you were using this more seriously, you'd probably want to remove missing values before computing the range and mean.