title: Recommended way to subset two vectors with the same index vector
body: <p>I am looking for an efficient way to subset two vectors with the same index vector. Efficient categories can be:</p>
  
  <ul>
  <li>Typo-save</li>
  <li>Memory Consumption</li>
  <li>Readability</li>
  <li>Computation Time</li>
  </ul>
  
  <p>Suppose I have two vectors <code>x</code> and <code>y</code></p>
  
  <pre><code>x &lt;- 1:10
  y &lt;- 10:1
  </code></pre>
  
  <p>and I want to overwrite the values of <code>x</code> with those of <code>y</code> when <code>x</code> is smaller than <code>y</code>. I can do this with (1):</p>
  
  <pre><code>x[x &lt; y] &lt;- y[x &lt; y]
  </code></pre>
  
  <p>But here I have to write <code>x &lt; y</code> twice, what has disadvantages to have a typo and when making an update I can forget to do this on both sides. So I can create an index vector (2):</p>
  
  <pre><code>idx &lt;- x &lt; y
  x[idx] &lt;- y[idx]
  rm(idx)
  </code></pre>
  
  <p>But here I create an additional vector which might need memory and time. I can also use a <code>for-loop</code> (3):</p>
  
  <pre><code>for(i in seq_along(x)) {
     if(x[i] &lt; y[i]) x[i] &lt;- y[i]
  }
  </code></pre>
  
  <p>This might be slow and I don't know if <code>seq_along(x)</code> allocates memory or not.
  I can use <code>delayedAssign</code> in an environment like (4):</p>
  
  <pre><code>(function() {
    delayedAssign("idx", x &lt; y)
    x[idx] &lt;&lt;- y[idx]
  })()
  </code></pre>
  
  <p>or (5):</p>
  
  <pre><code>evalq({
    delayedAssign("idx", x &lt; y)
    x[idx] &lt;&lt;- y[idx]}, envir = new.env(), enclos = parent.frame())
  </code></pre>
  
  <p>where I hope that <code>delayedAssign</code> does not create an <code>idx</code>vector in memory. There are several other possibilities already in <em>base</em> like:</p>
  
  <pre><code>x &lt;- ifelse(x &lt; y, y, x) #(6)
  x &lt;- sapply(seq_along(x), function(i) {if(x[i] &lt; y[i]) y[i] else x[i]}) #(7)
  with(data.frame(idx = x &lt; y), x[idx] &lt;&lt;- y[idx]) #(8)
  </code></pre>
  
  <p><code>x &lt; y</code> can be replaced with <code>which(x &lt; y)</code> what can reduce the vector size and improve <a href="https://stackoverflow.com/q/17340541/10488504">execution time</a>.</p>
  
  <p>In the end I'm not satisfied with all of those methods.</p>
  
  <p>Is there a recommended way to subset two vectors with one index vector? For me <em>Typo-save</em> and <em>Memory Consumption</em> are more important than <em>Execution time</em>.</p>
  
  <p>Is there a way to see the <em>Memory Consumption</em> of the different methods during execution like using <code>microbenchmark</code> to see execution time, or can it only be done by creating huge vectors and have a look on the system processes?</p>