title: Loop over rows of dataframe applying function with if-statement
body: <p>I'm new to R and I'm trying to sum 2 columns of a given dataframe, if both the elements to be summed satisfy a given condition. To make things clear, what I want to do is:</p>
  
  <pre><code>&gt; t.d&lt;-as.data.frame(matrix(1:9,ncol=3))
  &gt; t.d
    V1 V2 V3
    1  4  7  
    2  5  8  
    3  6  9  
  
  &gt; t.d$V4&lt;-rep(0,nrow(t.d))
  
  &gt; for (i in 1:nrow(t.d)){
  +   if (t.d$V1[i]&gt;1 &amp;&amp; t.d$V3[i]&lt;9){
  +     t.d$V4[i]&lt;-t.d$V1[i]+t.d$V3[i]}
  +     }
  
  &gt; t.d    
    V1 V2 V3 V4
    1  4  7  0
    2  5  8 10
    3  6  9  0
  </code></pre>
  
  <p>I need an efficient code, as my real dataframe has about 150000 rows and 200 columns. This gives an error:</p>
  
  <pre><code>t.d$V4&lt;-t.d$V1[t.d$V1&gt;1]+ t.d$V3[t.d$V3&gt;9] 
  </code></pre>
  
  <p>Is "apply" an option? I tried this:</p>
  
  <pre><code>t.d&lt;-as.data.frame(matrix(1:9,ncol=3))
  t.d$V4&lt;-rep(0,nrow(t.d))
  
  my.fun&lt;-function(x,y){
    if(x&gt;1 &amp;&amp; y&lt;9){
      x+y}
  }
  
  t.d$V4&lt;-apply(X=t.d,MAR=1,FUN=my.fun,x=t.d$V1,y=t.d$V3)
  </code></pre>
  
  <p>but it gives an error as well.
  Thanks very much for your help.</p>