Skip to content

Instantly share code, notes, and snippets.

@crstn
Created January 17, 2018 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crstn/bbb9fda973ccf93fa94f2a9fde38c9b1 to your computer and use it in GitHub Desktop.
Save crstn/bbb9fda973ccf93fa94f2a9fde38c9b1 to your computer and use it in GitHub Desktop.
This is a small fix of Carson Farmer's Voronoi Polygons function (http://carsonfarmer.com/2009/09/voronoi-polygons-with-r/) which also copies the input points layer's CRS string over to the output polygons.
voronoipolygons = function(layer) {
require(deldir)
crds = layer@coords
z = deldir(crds[,1], crds[,2])
w = tile.list(z)
polys = vector(mode='list', length=length(w))
require(sp)
for (i in seq(along=polys)) {
pcrds = cbind(w[[i]]$x, w[[i]]$y)
pcrds = rbind(pcrds, pcrds[1,])
polys[[i]] = Polygons(list(Polygon(pcrds)), ID=as.character(i))
}
SP = SpatialPolygons(polys, proj4string = layer@proj4string)
voronoi = SpatialPolygonsDataFrame(SP,
data = data.frame(x=crds[,1],
y=crds[,2],
row.names=sapply(slot(SP, 'polygons'),
function(x) slot(x, 'ID'))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment