Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
900 views
in Technique[技术] by (71.8m points)

r - Create convex hull polygon from points and save as shapefile

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...