I am currently trying to create a polygon shapefile from a list of polygons (study areas for biodiversity research).
Currently these polygons are stored in a list in this format:
$SEW22
[,1] [,2]
[1,] 427260.4 5879458
[2,] 427161.4 5879472
[3,] 427175.0 5879571
[4,] 427273.9 5879557
[5,] 427260.4 5879458
$SEW23
[,1] [,2]
[1,] 418011.0 5867216
[2,] 417912.0 5867230
[3,] 417925.5 5867329
[4,] 418024.5 5867315
[5,] 418011.0 5867216
I tried to simply write them as shpfile with writeOGR but the following error occurs:
> #write polygons to shp
> filenameshp <- paste('Forestplots')
> layername <- paste('Forestplots')
> writeOGR(obj=forest, dsn = filenameshp,
+ layer=layername, driver="ESRI Shapefile", overwrite_layer = TRUE)
Error in writeOGR(obj = forest, dsn = filenameshp, layer = layername, :
inherits(obj, "Spatial") is not TRUE
I read this tutorial by Barry Rowlingson to create spatialpolygons and thought I should probably first create a dataframe and did this:
forestm<-do.call(rbind,forest)
but this returned nothing useful as you can imagine, plus it lost the names of the plots.
As I am still new to R I also tried lots of different other approaches which sensefulness I could not fully judge but none returned what I hoped for and so I spare you with these random approaches.....
I am looking forward to your propositions.
Many thanks
P.S. I also tried the following as described in the spatialpolygons{sp} package:
> Polygons(forest, ID)
Error in Polygons(forest, ID) : srl not a list of Polygon objects
You can follow the approach described in this answer: https://gis.stackexchange.com/questions/18311/instantiating-spatial-polygon-without-using-a-shapefile-in-r.
Here's how to apply the approach to your case. First, I create a list of matrices as in your sample data:
Now
In the first step, we iterate through the list of matrices and apply the
Polygonfunction to each matrix to create a list ofPolygonobjects. In the second step, we iterate through this list to create aPolygonsobject, setting the ID of each element in this object to the corresponding name in the original list (e.g. "SEW22", "SEW23"). The third step creates aSpatialPolygonsobject. Finally, we create aSpatialPolygonsDataFrameobject. Here I have a dummy dataframe populated withNAs (note that the row names must correspond to the polygon IDs).Finally, write the data
This creates a new folder in your working directory:
Consult the linked answer for more details.