[R-sig-Geo] list of SpatialPolygons to SpatialPolygonsDataFrame

Roger Bivand Roger.Bivand at nhh.no
Thu Jan 17 18:50:10 CET 2013


On Thu, 17 Jan 2013, Emanuele Cordano wrote:

> Dear all,
>
> I have a list of SpatialPolygons-class objects containing only one 
> polygon for each list element. How can we gather each 
> SpatialPolygons-class objects list element in only one 
> SpatialPolygons-class object without using a 'for' loop?

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

>
> Our final target is to have this information in only one 
> SpatialPolygonsDataFrame-class which can easily created from one 
> SpatialPolygons-class object.
>
> Regards
> Thank you
>
> Emanuele Cordano
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

-- 
Roger Bivand
Department of Economics, NHH Norwegian School of Economics,
Helleveien 30, N-5045 Bergen, Norway.
voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no



More information about the R-sig-Geo mailing list