title: How do I generate a grid of coordinates within specified polygons in R?
body: <p>I have a list of two-dimensional polygons defined as two-column matrices of x and y coordinates in R.  They completely fill a square area and are mutually exclusive.  I want to use these polygon definitions to generate a fine grid of x,y coordinate values in which each value is identified by which polygon it falls into.  </p>
  
  <p>I have explored the <strong>sp</strong> package and can get my polygons into an object of class <code>SpatialPolygons</code>, but I don't know if that gets me closer to my goal.  With my polygons in a dataframe, I can use <code>ggplot</code> with <code>geom_polygon(aes(fill=ID))</code> to generate a plot of the polygons with coloring based on polygon ID.</p>
  
  <p>I can see several paths forward, but don't know how to accomplish any of them:</p>
  
  <ol>
  <li><p>A function that takes a polygon and generates a uniform grid of coordinates within the polygon boundaries. (My polygons are quite irregular, with many sides, so creating a custom function for them would be painful and error prone.)</p></li>
  <li><p>A function that takes a pair of x, y coordinates and my list of polygons and outputs which polygon the coordinates fall into.</p></li>
  <li><p>A function that takes my ggplot-generated plot and converts the colors into a grid of numeric coordinate values that I could read back into R.</p></li>
  </ol>
  
  <p>There may be also be other approaches that I'm not imagining.  I have to believe that other people have had this same need before, but extensive searching has not led me to any existing functions that do what I need.  </p>