rspatialr-sp

R - SpatialPolygonsDataFrame from a list of SpatialPolygons


I´m looking for a way to create a SpatialPolygonsDataFrame from a list of SpatialPolygons?

In the following there´s an example of a list of Polygons from which a SpatialPolygonsDataFrame, containing all Polygons of the list, should be created.

EDIT: The SpatialPolygonsDataFrame must be created from the list of SpatialPolygons! As my original data doesn´t contains SpatialPolygons as separate values but the list of SpatialPolygons. The way I received this list is different form the one in the example. I posted the example to show the data structure of the list.

example of a list of SpatialPolygons taken from https://stat.ethz.ch/pipermail/r-sig-geo/2013-January/017225.html:

library(sp)
grd <- GridTopology(c(0.5, 0.5), c(1, 1), c(6, 6))
Spol <- as(grd, "SpatialPolygons")
list_of_SPolsu <- lapply(slot(Spol, "polygons"), function(x)
   SpatialPolygons(list(x)))
list_of_SPols <- lapply(slot(Spol, "polygons"), function(x) {
   Pol <- x
   slot(Pol, "ID") <- "1"
   SpatialPolygons(list(Pol))
})

Regards!


Solution

  • Try this:

    #Creating a dataframe with Spol IDs
    Spol_df<- as.data.frame(sapply(slot(Spol, "polygons"), function(x) slot(x, "ID")))
    
    #Making the IDs row names 
    row.names(Spol_df) <- sapply(slot(Spol, "polygons"), function(x) slot(x, "ID"))
    
    # Making the spatial polygon data frame
    Spol_SPDF <- SpatialPolygonsDataFrame(Spol, data =Spol_df)
    

    Let me know if it worked

    Edit:

    Just to make the answer complete according to the Edit in the question... The solution on how to make a SpatialPolygon from a list of polygons comes from the provided link:

    #Getting polygon IDs
    IDs <- sapply(list_of_SPols, function(x)
      slot(slot(x, "polygons")[[1]], "ID"))
    
    #Checking
    length(unique(IDs)) == length(list_of_SPols)
    
    #Making SpatialPolygons from list of polygons
    Spol <- SpatialPolygons(lapply(list_of_SPols,
                                    function(x) slot(x, "polygons")[[1]]))