Skip to content
Prev 1018 / 29559 Next

[ESRI-L] outline polygons of point clumps

On Fri, 12 May 2006, Xiaohua Dai wrote:

            
set.seed(1)
xy <- matrix(runif(500, 0, 10), ncol=2)
xy_clusts <- hclust(dist(xy), method="complete")
cl_10 <- cutree(xy_clusts, 10)
which_cl_10 <- tapply(1:nrow(xy), cl_10, function(i) xy[i,])
chulls_cl_10 <- lapply(which_cl_10, function(x) x[chull(x),])
# so far as before - now:

n <- length(chulls_cl_10)
library(sp)
polygons <- lapply(1:n, function(i) {
  chulls_cl_10[[i]] <- rbind(chulls_cl_10[[i]], chulls_cl_10[[i]][1,])
# the convex hulls do not join first and last points, so we copy here
  Polygons(list(Polygon(coords=chulls_cl_10[[i]])), ID=i) })
out <- SpatialPolygonsDataFrame(SpatialPolygons(polygons),
  data=data.frame(ID=1:n))
plot(out)
# note standard-violating intersecting polygons!
tempfile <- tempfile()
library(maptools)
writePolyShape(out, tempfile)
in_again <- readShapePoly(tempfile)
plot(in_again, border="blue", add=TRUE)

The trick is to construct a SpatialPolygons object defined in the sp 
package, and write it and a single data field out to a shapefile. The 
shapefile is strictly wrong, because the polygons can intersect, but at 
least it's something to start with.

Roger