Note that there are some explanatory texts on larger screens.

plurals
  1. POTest for equality among all elements of a single vector
    text
    copied!<p>I'm trying to test whether all elements of a vector are equal to one another. The solutions I have come up with seem somewhat roundabout, both involving checking <code>length()</code>.</p> <pre><code>x &lt;- c(1, 2, 3, 4, 5, 6, 1) # FALSE y &lt;- rep(2, times = 7) # TRUE </code></pre> <p>With <code>unique()</code>:</p> <pre><code>length(unique(x)) == 1 length(unique(y)) == 1 </code></pre> <p>With <code>rle()</code>:</p> <pre><code>length(rle(x)$values) == 1 length(rle(y)$values) == 1 </code></pre> <p>A solution that would let me include a tolerance value for assessing 'equality' among elements would be ideal to avoid <a href="http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f" rel="noreferrer">FAQ 7.31</a> issues.</p> <p>Is there a built-in function for type of test that I have completely overlooked? <code>identical()</code> and <code>all.equal()</code> compare two R objects, so they won't work here.</p> <p><strong>Edit 1</strong></p> <p>Here are some benchmarking results. Using the code:</p> <pre><code>library(rbenchmark) John &lt;- function() all( abs(x - mean(x)) &lt; .Machine$double.eps ^ 0.5 ) DWin &lt;- function() {diff(range(x)) &lt; .Machine$double.eps ^ 0.5} zero_range &lt;- function() { if (length(x) == 1) return(TRUE) x &lt;- range(x) / mean(x) isTRUE(all.equal(x[1], x[2], tolerance = .Machine$double.eps ^ 0.5)) } x &lt;- runif(500000); benchmark(John(), DWin(), zero_range(), columns=c("test", "replications", "elapsed", "relative"), order="relative", replications = 10000) </code></pre> <p>With the results:</p> <pre><code> 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 </code></pre> <p>So it looks like <code>diff(range(x)) &lt; .Machine$double.eps ^ 0.5</code> is fastest.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload