title: How do I find the polygon nearest to a point in R?
body: <p>I have a spatial points data frame and a spatial polygons data frame. For example, my polygons would be a polygon for each block in Manhattan. And the points are people, which are scattered all over, sometimes falling in the middle of a street, which is not part of a polygon.</p>
  
  <p>I know how to check if a point is contained inside a polygon, but how could I assign points to their closest polygon?</p>
  
  <pre><code>## Make some example  data
  set.seed(1)
  library(raster)
  library(rgdal)
  library(rgeos)
  p &lt;- shapefile(system.file("external/lux.shp", package="raster"))
  p2 &lt;- as(1.5*extent(p), "SpatialPolygons")
  proj4string(p2) &lt;- proj4string(p)
  pts &lt;- spsample(p2-p, n=10, type="random")
  
  ## Plot to visualize
  plot(pts, pch=16, cex=.5,col="red")
  plot(p, col=colorRampPalette(blues9)(12), add=TRUE)
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/4QU8K.png" alt="enter image description here"></p>