title: How to filter values if are within ranges to add as a new column in data frame
body: <p>I have a big data frames named "X" and "Y" that look like this: </p>
  
  <pre><code>Y &lt;- data.frame(chrom = c(21,21,21,21,21),
              chromStart = c(14720086, 14759761, 14799594, 14847192, 14860997), 
              chromEnd = c(14722086, 14761761, 14801594, 14849192, 14862997),
              TargetGenes = c("ENSG00000185390", "ENSG00000175302",
                              "ENSG00000175302", "ENSG00000219280", "ENSG00000226930"))
  
  X &lt;- data.frame(POS = c(14720573, 14720652, 14721241, 14721279, 14721280))
  </code></pre>
  
  <p>and here what I have tried to do:</p>
  
  <pre><code>X$TargetGene &lt;- apply(X$POS, 1, function(v) ifelse(length(k &lt;- which(v &gt;= Y$chromStart &amp; v &lt;= Y$chromEnd))&gt;0,
                  as.character(Y$TargetGenes[k]), NA))
  </code></pre>
  
  <p>I am looking for an R solution to check for every row in "X" and finds if X$POS is between Y$chrStart and Y$chrEnd, so then adding the correspond Y$ID to "X" as a new column named "TargetGene". </p>
  
  <p>There may be few values from X$POS that fit into a range in Y data frame. Also, it is possible for some X$POS that do not find any match range in Y data frame. </p>
  
  <p>p.s. the values of Y$chr are the same. </p>
  
  <p>Desired output:</p>
  
  <pre><code>&gt; X
  POS        TargetGene
  14720573   ENSG0000017
  14720652   ENSG0000017
  14721241      &lt;NA&gt;
  15221776   ENSG0000022
  </code></pre>
  
  <p>I do approcciate for any insight.</p>