title: Conditional dataframe mutations in R with magrittr and dplyr
body: <p>I would like to use the succinctness of magrittr and dplyr to copy single values between rows in a subset of columns based on the values in other columns. This is a simple example; I want to apply this idea to many columns of a large dataset with multiple conditions within a long pipe of commands.</p>
  
  <p>Take the dataframe <code>df &lt;- data.frame(a = 1:5, b = 6:10, x = 11:15, y = 16:20)</code>:</p>
  
  <pre><code>a   b   x   y
  
  1   6   11  16
  2   7   12  17
  3   8   13  18
  4   9   14  19
  5   10  15  20
  </code></pre>
  
  <p>For the row where <code>a = 5</code>, I would like to replace the values of <code>x</code> and <code>y</code> with those in the row where <code>b = 7</code>, to give:</p>
  
  <pre><code>a   b   x   y
  
  1   6   11  16
  2   7   12  17
  3   8   13  18
  4   9   14  19
  5   10  12  17
  </code></pre>
  
  <p>This attempt fails:</p>
  
  <pre><code>foo &lt;- function(x){ifelse(df$a == 5, df[df$b == 7, .(df$x)], x)}
  df %&lt;&gt;%  mutate_each(funs(foo), x, y)
  </code></pre>
  
  <p>The closest I can get is:</p>
  
  <pre><code>bar &lt;- function(x){ifelse(df$a == 5, df[df$b == 7, "x"], x)}
  df %&lt;&gt;%  mutate_each(funs(bar), x, y)
  </code></pre>
  
  <p>but this is incorrect as it replaces both values with the value from <code>x</code>, rather than <code>x</code> and <code>y</code> respectively.</p>
  
  <p>Thanks for the advice.</p>