SpatialPolygons - Creating a set of polygons in R from coordinates

前端 未结 1 1052
南笙
南笙 2020-12-03 02:03

I am trying to take create a set of polygons from vertex locations, saved in X,Y format.

Here is an example of my data - each row represents the vertices for one pol

相关标签:
1条回答
  • 2020-12-03 02:15

    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)
    

    enter image description here

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

    enter image description here

    0 讨论(0)
提交回复
热议问题