title: dplyr mutate with conditional values
body: <p>In a large dataframe ("myfile") with four columns I have to add a fifth column with values conditionally based on the first four columns.</p>
  
  <p>Prefer answers with <code>dplyr</code> and <code>mutate</code>, mainly because of its speed in large datasets.</p>
  
  <p>My dataframe looks like this:</p>
  
  <pre><code>  V1 V2 V3 V4
  1  1  2  3  5
  2  2  4  4  1
  3  1  4  1  1
  4  4  5  1  3
  5  5  5  5  4
  ...
  </code></pre>
  
  <p>The values of the fifth column (V5) are based on some conditional rules:</p>
  
  <pre><code>if (V1==1 &amp; V2!=4) {
    V5 &lt;- 1
  } else if (V2==4 &amp; V3!=1) {
    V5 &lt;- 2
  } else {
    V5 &lt;- 0
  }
  </code></pre>
  
  <p>Now I want to use the <code>mutate</code> function to use these rules on all rows (to avoid slow loops). Something like this (and yes, I know it doesn't work this way!):</p>
  
  <pre><code>myfile &lt;- mutate(myfile, if (V1==1 &amp; V2!=4){V5 = 1}
      else if (V2==4 &amp; V3!=1){V5 = 2}
      else {V5 = 0})
  </code></pre>
  
  <p>This should be the result:</p>
  
  <pre><code>  V1 V2 V3 V4 V5
  1  1  2  3  5  1
  2  2  4  4  1  2
  3  1  4  1  1  0
  4  4  5  1  3  0
  5  5  5  5  4  0
  </code></pre>
  
  <p>How to do this in <code>dplyr</code>? </p>