title: Better way to do conditional-sum on df than for-loop?
body: <p>I am doing sum on dataframes with for loop. I know that normaly is not a good idea to loop in R and that it is a better way to do it using sapply or aggregate but I just don t see how to use it in my case . </p>
  
  <p>I want to sum one column based on condition of two columns in an iterative way.</p>
  
  <p>Here is what i want to do in a better way for you to understand:</p>
  
  <pre><code>sample  &lt;- data.frame( ID = c("bli","bla","blou","qhq","bidi","bada","bodo"),
          A = c(1,0,1,1,0,1,1) , 
          B = c(0,1,1,0,0,1,0) ,
          C = c(0,1,1,0,0,1,1) 
  
                    )
  
  
   g  &lt;-  NULL 
  bli  &lt;- 1:length(sample)
  for (j in 2:length(sample)) {
    a &lt;- sum(subset(sample,sample[,c(j) ] ==1 , c(j)))
    for (i in 2:length(sample)) 
      if (bli[j] != bli[i]) {
      b  &lt;- sum(subset(sample,sample[,c(j)] ==1 &amp; sample[,c(i) ] ==1 , c(i)))
      c &lt;- names(sample[j])
      d &lt;- names(sample[i])
      e  &lt;- cbind(c,d,a,b)
      f  &lt;- data.frame(e)
      g &lt;-  rbind(g,f) } 
    else {
      NULL
  }
  
    }
  g
  </code></pre>
  
  <p>Thanks</p>