title: Apply conditional function to a dataframe
body: <p>I want to apply a function to rows of a data frame. The function is conditional on the value of one column being greater than the value in another column. If the condition is met I take the element from two (other) columns and multiply them, the result is then added to a new column. If the initial condition is not met there is no multiplication and an original value is copied to the new column.</p>
  
  <p>Create some data:</p>
  
  <pre><code>var0 &lt;- c("A", "B", "C", "D", "E")
  var1 &lt;- rep(c(105,200), each = 5)
  var2 &lt;- c(110:114, 25:29)
  var3 &lt;- rep(c(560,135), each = 5)
  var4 &lt;- rep(c(0.5,0.2), each = 5)
  my_df &lt;- as.data.frame(cbind(var0, var1, var2, var3, var4))    
  </code></pre>
  
  <p>Have a look at the data:</p>
  
  <pre><code>       var0 var1 var2 var3 var4
      1     A  105  110  560  0.5
      2     B  105  111  560  0.5
      3     C  105  112  560  0.5
      4     D  105  113  560  0.5
      5     E  105  114  560  0.5
      6     A  200   25  135  0.2
      7     B  200   26  135  0.2
      8     C  200   27  135  0.2
      9     D  200   28  135  0.2
      10    E  200   29  135  0.2
  </code></pre>
  
  <p>My attempt at writing the code:</p>
  
  <pre><code>apply(my_df, 1, function(x) {
    if(x$var3 &gt; x$var1) {
      x$output &lt;- x$var2 * x$var4
      } else {
        x$output &lt;- x$var2
      }
        return(x)
    })
  </code></pre>
  
  <p>What the result should look like:</p>
  
  <pre><code>        var0 var1 var2 var3 var4 output
      1     A  105  110  560  0.5   55.0
      2     B  105  111  560  0.5   55.5
      3     C  105  112  560  0.5   56.0
      4     D  105  113  560  0.5   56.5
      5     E  105  114  560  0.5   57.0
      6     A  200   25  135  0.2   25.0
      7     B  200   26  135  0.2   26.0
      8     C  200   27  135  0.2   27.0
      9     D  200   28  135  0.2   28.0
      10    E  200   29  135  0.2   29.0
  </code></pre>
  
  <p>Because var3 is greater than var1 in the first 5 rows var2 * var4 occurs, in the last 5 rows the condition is not met so var2 is simply copied to the output column.</p>