SpatialPolygons - Creating a set of polygons in R from coordinates

最后都变了- 提交于 2019-11-27 12:53:05

There's some information at ?'SpatialPolygons-class', but you more-or-less want to do the following:

polys <- SpatialPolygons(list(
  Polygons(list(Polygon(matrix(square[1, ], ncol=2, byrow=TRUE))), ID[1]),
  Polygons(list(Polygon(matrix(square[2, ], ncol=2, byrow=TRUE))), ID[2])
))

plot(polys)

The basic gist is that you need to create Polygon objects (e.g., from 2-column matrices with x coordinates in the first column and y coordinates in the second). These are combined in lists to create Polygons objects (each of which should have a unique ID). These Polygons objects are combined in a list to create a SpatialPolygons object. You can add a CRS if you like, with the proj4string argument to SpatialPolygons (see ?SpatialPolygons).

To write it out to an ESRI Shapefile, you'll need to convert it to a SpatialPolygonsDataFrame object by combining the polys object we created and some data. We'll just add the IDs as data for lack of anything more interesting.

polys.df <- SpatialPolygonsDataFrame(polys, data.frame(id=ID, row.names=ID))

and then write it out...

writeOGR(polys.df, '.', 'fancysquares', 'ESRI Shapefile')

The second argument ('.') says to write it out to the current working directory.


EDIT

To quickly create a SpatialPolygonsDataFrame when you have many rows describing polygons, you could use the following:

# Example data
square <- t(replicate(50, {
  o <- runif(2)
  c(o, o + c(0, 0.1), o + 0.1, o + c(0.1, 0), o)
}))
ID <- paste0('sq', seq_len(nrow(square)))

# Create SP
polys <- SpatialPolygons(mapply(function(poly, id) {
  xy <- matrix(poly, ncol=2, byrow=TRUE)
  Polygons(list(Polygon(xy)), ID=id)
}, split(square, row(square)), ID))

# Create SPDF
polys.df <- SpatialPolygonsDataFrame(polys, data.frame(id=ID, row.names=ID))

plot(polys.df, col=rainbow(50, alpha=0.5))

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!