title: Extracting n rows above and below a given row number (variable n)
body: <p>I have a dataset "dat" as follows:</p>
  
  <pre><code>      ChromKey CHROM      POS   ID   REF ALT length                   
  11438        1  chr1 27023450 &lt;NA&gt;  AGCG   A   4 
  11755        1  chr1 27023767 &lt;NA&gt;    CA   C   3       
  12521        1  chr1 27057930 &lt;NA&gt;    GA   G   2                
  13174        1  chr1 27088681 &lt;NA&gt;    TC   T   3                   
  14861        1  chr1 27100181 &lt;NA&gt;  CGCA   C   2     
  15593        1  chr1 27101426 &lt;NA&gt; TCTAA   T   5 
  </code></pre>
  
  <p>This dataset was created as a subset of another much larger dataset that contains each of the rows in dat and more. Let's call this original full dataset "dat.ori". (The numbers on the extreme left are the row numbers from the dat.ori dataset that have been subsetted to create dat).</p>
  
  <p>From the original larger dataset I would like to create a dataset such that I can extract the rows that are in dat along with n rows above and below that row number, where n is the value given under the variable <em>length</em> in dat. For example, the rows I need extracted from dat.ori are </p>
  
  <pre><code>11434, 11435, 11436, 11437, 11438, 11439, 11440, 11441, 11442, 11752, 11753, 
  11754, 11755, 11756, 11757, 11758 and so on
  </code></pre>
  
  <p>That is 4 rows above and below 11438, 3 rows above and below 11755, 2 rows above and below 12521 etc.</p>
  
  <p>Is there a way to do this in R? Many thanks! :)</p>
  
  <p>(Apologies, its not the most reproducible example but I will try and edit this so that respondents can reproduce the example)</p>
  
  <p>UPDATE: Here's what I did (from: <a href="https://stackoverflow.com/questions/13155609/returning-above-and-below-rows-of-specific-rows-in-r-dataframe">Returning above and below rows of specific rows in r dataframe</a>)</p>
  
  <pre><code>myRows=c(rownames(dat))
  rowRanges &lt;- lapply(which(rownames(dat.ori) %in% myRows), function(x) x + c(-1:1))
  final=lapply(rowRanges, function(x) dat.ori[x, ])
  </code></pre>
  
  <p>This gives me exactly what I need but it gives me just <em>one</em> row above and below (set by c(-1:1)). What I need is this to be tweaked so that I get n rows above and below where n is determined by dat$length </p>