title: How to use a for loop to select values across two columns in a data frame to produce a new output
body: <p>In R, I have spatial coordinate data for a grid of data with x and y coordinates in two columns from 0-100. </p>
  
  <p>I would like to loop over both x and y columns to identify specific ranges on a 10x10 subgrid, then output a new subregion ID in another column</p>
  
  <p>For example, I would like select a range of values that match both those in the x coordinates column (e.g. 0-9) and the y coordinates (e.g. 20-29) to produce an output in a new column called SubRegion. Of course it would then iterate through to match all of the potential ~100 subregions. (In reality my data are a bit more complicated but this is a simplified explanation)</p>
  
  <p>I've added a new column to the dataframe and written a for loop that is successful across one column but unsuccessful with 2 columns of data.</p>
  
  <p>The following code is unsuccessful in producing a result on 2 columns </p>
  
  <pre><code>df$SubRegion &lt;- NA # added a new sub region column to df
  
  for (i in 1:nrow(df)){ 
    if (df$yCord[i] &gt; 0.00 &amp; df$yCord &lt; 9.99 &amp; df$xCord &gt; 0.00 &amp; df$xCord &lt; 9.99){df$SubRegion [i]=1}
  
    if (df$yCord[i] &gt; 10.00 &amp; df$yCord &lt; 19.99 &amp; df$xCord &gt; 0.00 &amp; df$xCord &lt; 9.99){df$SubRegion [i]=2}
  
    if (df$yCord[i] &gt; 20.00 &amp; df$yCord &lt; 29.99 &amp; df$xCord &gt; 0.00 &amp; df$xCord &lt; 9.99){df$SubRegion [i]=3}
  
    }
  </code></pre>
  
  <p>If I simplify the code to select a range on one column, I can get it to work:</p>
  
  <pre><code>for (i in 1:nrow(df)){ 
    if (df$yCord[i] &gt; 0.00 &amp; df$yCord &lt; 9.99{df$SubRegion [i]=1}
  
    if (df$yCord[i] &gt; 10.00 &amp; df$yCord &lt; 19.99{df$SubRegion [i]=2}
  
    if (df$yCord[i] &gt; 20.00 &amp; df$yCord &lt; 29.99{df$SubRegion [i]=3}
  </code></pre>
  
  <p>I would like an output that looks like this:</p>
  
  <pre><code>yCord   | xCord  | SubRegion
  1       |3       |1
  1       |9       |1
  10      |3       |2
  22      |5       |3
  </code></pre>
  
  <p>Instead I'm not getting any results, just NA</p>