I am trying to check if all elements of a vector are equal to each other. The solutions I came up with seem a bit workaround, including length() checking.
x <- c(1, 2, 3, 4, 5, 6, 1)
With unique() :
length(unique(x)) == 1 length(unique(y)) == 1
With rle() :
length(rle(x)$values) == 1 length(rle(y)$values) == 1
A solution that would allow me to include the tolerance value for evaluating "equality" among the elements would be ideal to avoid FAQ 7.31 .
Is there a built-in function for the type of test that I completely ignored? identical() and all.equal() compare two R objects, so they will not work here.
Change 1
Here are some benchmarking results. Using the code:
library(rbenchmark) John <- function() all( abs(x - mean(x)) < .Machine$double.eps ^ 0.5 ) DWin <- function() {diff(range(x)) < .Machine$double.eps ^ 0.5} zero_range <- function() { if (length(x) == 1) return(TRUE) x <- range(x) / mean(x) isTRUE(all.equal(x[1], x[2], tolerance = .Machine$double.eps ^ 0.5)) } x <- runif(500000); benchmark(John(), DWin(), zero_range(), columns=c("test", "replications", "elapsed", "relative"), order="relative", replications = 10000)
With the results:
test replications elapsed relative 2 DWin() 10000 109.415 1.000000 3 zero_range() 10000 126.912 1.159914 1 John() 10000 208.463 1.905251
It looks like diff(range(x)) < .Machine$double.eps ^ 0.5 is the fastest.
equality vector r
kmm Jan 20 2018-11-21T00: 00Z
source share