title: sum columns in a data.frame based on conditions from another dataframe in R
body: <p>I have two data frames, <code>a</code> and <code>b</code>. </p>
  
  <p>For each row in <code>b</code>, I want to find all <code>start,end</code> in <code>a</code> that are within the <code>start,end</code> of <code>b</code>, and then sum differences of <code>start,end</code> of this particular subset of <code>a</code>, and store it as a new column in <code>b</code>. I'm using a <code>for</code> loop but is there a more efficient way to do this with <code>apply</code> in R?</p>
  
  <pre><code># data.frame a  
  a &lt;- data.frame(chrom=1L, start=as.integer(c(2,4,7,11)), end=as.integer(c(3,6,9,15)))
  # chrom start end  
  #     1     2   3  
  #     1     4   6  
  #     1     7   9        
  #     1    11  15  
  
  # data.frame b  
  b &lt;- data.frame(chr=1L, start=as.integer(c(2,11)), end=as.integer(c(10,20)))
  # chrom start end  
  #     1     2  10  
  #     1    11  20  
  
  # code
  result=c()
  for (i in 1:dim(b)[1]) { 
      # find start,end in A that are within    
      a_subset = a[which(a$chrom == b[i, ]$chrom &amp; 
                   a$start &gt;= b[i, ]$start &amp; 
                   a$end &lt;= b[i, ]$end), ]
  
      result = append(result, sum(a_subset$end - a_subset$start))  
  }
  c = cbind(b, result)
  
  # data.frame c
  # chrom start end result
  #     1     2  10      5
  #     1    11  20      4
  </code></pre>