Create convex hull polygon from points and save as shapefile

user3310782 picture user3310782 · Sep 1, 2014 · Viewed 16.8k times · Source

Needing some help re a conversion problem in R.

I've got calculated the convex hull of a cloud of points. I'd like, from the points forming the convex hull, to build a polygon object and save that as a shapefile that can be read by a GIS software (ArcMap or the like).

My code looks like this:

gps <- read.csv(f)  ##reads the lat-long coordinates  file 
x <- gps$LONGITUDE  ##tells R which columns is which
y <- gps$LATITUDE
z<-chull(x,y)       ##calculates the convex hull --this is just a list of x-y points, N vertex 
dfHull <-cbind(x[z],y[z])  ##the convex hull expressed as a list of selected x-y points
plot(dfHull)     ##this plots the vertex of the polygon, just a check
lines(dfhull)    ##plots the polygon in screen

##generate polygon shapefile, from dfHull, and save it externally as a shapefile ???

The source file only contains lat-long coordinates, e.g:

52.73336     N  0.365974
52.7332  N  0.366051
52.73289     N  0.36636
52.73297     N  0.366258
52.73298     N  0.366243
52.733   N  0.366112
52.73308     N  0.365942
52.73317     N  0.365881
52.73321     N  0.36593
52.73328     N  0.365942
52.73352     N  0.36579
52.73362     N  0.365678
52.73391     N  0.365536
52.7373  N  0.36543
52.73289     N  0.36728

I know there are packages (rgdal,maptools,..) to help with these, but I'm very unfamiliar with spatial stuff. Really all I need is to generate the polygon object and save that as shapefile.

Any help appreciated. Thanks in advance, dev.

Answer

rcs picture rcs · Sep 1, 2014

Here is a simple example to create a SpatialPolygonsDataFrame, which can be saved as a shapefile with rgdal::writeOGR():

set.seed(1)
dat <- matrix(stats::rnorm(2000), ncol = 2)
ch <- chull(dat)
coords <- dat[c(ch, ch[1]), ]  # closed polygon

plot(dat, pch=19)
lines(coords, col="red")

convex hull

library("sp")
library("rgdal")

sp_poly <- SpatialPolygons(list(Polygons(list(Polygon(coords)), ID=1)))
# set coordinate reference system with SpatialPolygons(..., proj4string=CRS(...))
# e.g. CRS("+proj=longlat +datum=WGS84")
sp_poly_df <- SpatialPolygonsDataFrame(sp_poly, data=data.frame(ID=1))
writeOGR(sp_poly_df, "chull", layer="chull", driver="ESRI Shapefile")