Skip to content
Prev 17198 / 29559 Next

list of SpatialPolygons to SpatialPolygonsDataFrame

On Thu, 17 Jan 2013, Emanuele Cordano wrote:

            
These are the *apply functions - here first making your input object:

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

which also messes things up by giving all the Polygons objects the same ID 
- if all your IDs are known to be unique, you can simplify from:

IDs <- sapply(list_of_SPols, function(x)
   slot(slot(x, "polygons")[[1]], "ID"))
length(unique(IDs)) == length(list_of_SPols)

Spol1 <- SpatialPolygons(lapply(1:length(list_of_SPols), function(i) {
   Pol <- slot(list_of_SPols[[i]], "polygons")[[1]]
   slot(Pol, "ID") <- as.character(i)
   Pol
}))

giving a sequence of new IDs, to:

IDsu <- sapply(list_of_SPolsu, function(x)
   slot(slot(x, "polygons")[[1]], "ID"))
length(unique(IDsu)) == length(list_of_SPolsu)

Spol2 <- SpatialPolygons(lapply(list_of_SPolsu,
   function(x) slot(x, "polygons")[[1]]))

When the input IDs are unique, you can also use them to help you order and 
add the data.frame in the next step.

You can also use the names of list components:

set.seed(1)
IDs <- sample(c(LETTERS, letters), 36)
names(list_of_SPols) <- IDs
Spol3 <- SpatialPolygons(lapply(1:length(list_of_SPols), function(i) {
   Pol <- slot(list_of_SPols[[i]], "polygons")[[1]]
   slot(Pol, "ID") <- names(list_of_SPols)[i]
   Pol
}))

if that is more convenient, provided that they are unique.

Checking:

row.names(Spol)
row.names(Spol1)
row.names(Spol2)
row.names(Spol3)

Hope this helps,

Roger