Just out of interest: I'm creating a SpatialPolygon (R with package "sp") with a number of Polygons within. Is there a way to loop this task? I'm doing it manually as follows. The Polygons consist of 5 points each (i.e. a square) that are stored together in a larger matrix ("bbox_matrix_sp").

    Polygons(list(Polygon(bbox_matrix_sp[1:5,])), "reh1"),
    Polygons(list(Polygon(bbox_matrix_sp[6:10,])), "reh2"),
    Polygons(list(Polygon(bbox_matrix_sp[11:15,])), "reh3"),
    Polygons(list(Polygon(bbox_matrix_sp[16:20,])), "reh4"),
    Polygons(list(Polygon(bbox_matrix_sp[21:25,])), "reh5"),
    Polygons(list(Polygon(bbox_matrix_sp[26:30,])), "reh6"),
    Polygons(list(Polygon(bbox_matrix_sp[31:35,])), "reh7"),
    Polygons(list(Polygon(bbox_matrix_sp[36:40,])), "reh8"),
    Polygons(list(Polygon(bbox_matrix_sp[41:45,])), "reh9"),
    Polygons(list(Polygon(bbox_matrix_sp[46:50,])), "reh10"),
    Polygons(list(Polygon(bbox_matrix_sp[51:55,])), "reh11"),
    Polygons(list(Polygon(bbox_matrix_sp[56:60,])), "reh12"),
    Polygons(list(Polygon(bbox_matrix_sp[61:65,])), "reh13")
    )) -> sp_re_alle

This seems a little bit tedious, especially if the number of Polygons within the SpatialPolygon increases.

Is there a faster, more elegant way?


Yes, using a lapply, e.g.:

x = c(0,1,1,0,0)
y = c(0,0,1,1,0)
bbox_matrix_sp = cbind(rep(x,13),rep(y,13))
sp_re_alle = SpatialPolygons(lapply(1:13, function(x) Polygons(list(Polygon(bbox_matrix_sp[((x-1)*5+1):(x*5),])), paste0("reh",x))))

in case you are converting grids into polygons, there are direct conversion methods in sp, as in

demo(meuse, ask = FALSE) 
m.p = as(meuse.grid, "SpatialPolygonsDataFrame")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.