Skip to content

Instantly share code, notes, and snippets.

@crstn crstn/voronoi.r
Created Jan 17, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.