title: How do I extract raster values from polygon data then join into spatial data frame?
body: <p>I would like to merge polygon data and raster data into one dataframe for purposes of then using randomForests package in R.<br>
  This involves first extracting the mean raster value per polygon.  </p>
  
  <p>So far, I have the following:  </p>
  
  <pre><code>#load libraries
  library(raster)
  library(rgdal)
  library(sp)
  library(maptools)
  
  #import raster data 
  r &lt;- raster("myRasterdata.tif")
  
  #import polygon data 
  p &lt;- readShapePoly("myPolydata.shp")
  
  #extract mean raster value for each polygon
  ExtractMyData &lt;- extract(r, p, small=TRUE, fun=mean, na.rm=TRUE, df=FALSE,  nl=1, sp=TRUE)
  # note I have also tried this with df=TRUE and sp=FALSE
  </code></pre>
  
  <p>The output is a matrix, which I can write to a dataframe. But it does not have the spatial coordinates or the original polygon IDs, so I don't know how to join the output into the same database.I thought the sp=TRUE argument would do this, but it doesn't seem to work. </p>
  
  <p>Note that I will actually have to convert the polygons to points (using a centroid method?) for purposes of RandomForests so I could guess what I really want is to join the mean raster values joined to points, not polygons. </p>
  
  <p>Any suggestions would be greatly appreciated. Thank you!! </p>