title: How could I make this R snippet faster and more R-ish?
body: <p>Coming from various other languages, I find R powerful and intuitive, but I am not thrilled with its performance. So I decided to try to improve some snippet I wrote and learn how to code better in R.</p>
  
  <p>Here's a function I wrote, trying to determine if a vector is binary-valued (two distinct values or just one value) or not:</p>
  
  <pre><code>isBinaryVector &lt;- function(v) {
    if (length(v) == 0) {
      return (c(0, 1))
    }
    a &lt;- v[1]
    b &lt;- a
    lapply(v, function(x) { if (x != a &amp;&amp; x != b) {if (a != b) { return (c()) } else { b = x }}})
    if (a &lt; b) {
      return (c(a, b))
    } else {
      return (c(b, a))
    }
  }
  </code></pre>
  
  <p>EDIT: This function is expected to look through a vector then return <code>c()</code> if it is not binary-valued, and return <code>c(a, b)</code> if it is, a being the small value and b being the larger one (if a == b then just <code>c(a, a)</code>. E.g., for</p>
  
  <pre><code>  A B C
  1 1 1 0
  2 2 2 0
  3 3 1 0
  </code></pre>
  
  <p>I will <code>lapply</code> this <code>isBinaryVector</code> and get:</p>
  
  <pre><code>$A
  [1] 1 1
  
  $B
  [1] 1 1
  
  $C
  [1] 0 0
  </code></pre>
  
  <p>The time it took on a moderate sized dataset (about 1800 * 3500, 2/3 of them are binary-valued) is about 15 seconds. The set contains only floating-point numbers.</p>
  
  <p>Is there anyway I could do this faster?</p>
  
  <p>Thanks for any inputs!</p>