2

I have a loaded .csv table in R containing xlongl, xlongr, ylatb, ylatup values (EPSG:4326). Each row indicates with its combination of lat/long the extent of one rectangled polygon.

> mydata
    xlongl     xlongr      ylatb    ylatup
  1    13.500000  15.500000   6.000000  8.000000
  2     9.000000  22.000000   0.000000 20.000000
  3    18.000000  27.000000  -5.000000  9.000000
  4     9.000000  18.000000  -5.000000  9.000000

Referring to this post entry it is possible to nest the extent function, from the raster library, in as to create a SpatialPolygons object. It seems to be the smarter solution instead of using the more complex way from matrix/data frame(lat/long) -> Polygon -> Polygons -> SpatialPolygon

Could someone help me to develop a coding containing a loop that built the extent as SpatialPolygon object one row after another? And that can finally merge the created single SpatialPolygon objects to one by maintaining the original order of the table?

1 Answer 1

4

You could nest extent and as(..., "SpatialPolygons") inside an apply loop. This helps you create a list of "SpatialPolygons" objects which, using e.g. bind from raster, can subsequently be appended to one another.

library(raster)

## sample data
dat <- data.frame(xlongl = c(13.5, 9, 18, 9), 
                  xlongr = c(15.5, 22, 27, 18),
                  ylatb = c(6, 0, -5, -5),
                  ylatup = c(8, 20, 9, 9))

## create polygons from extents
pys <- apply(dat, 1, FUN = function(x) as(extent(x), "SpatialPolygons"))

## bind single polygons
py <- do.call("bind", pys)
proj4string(py) <- "+init=epsg:4326"

py
# class       : SpatialPolygons 
# features    : 4 
# extent      : 9, 27, -5, 20  (xmin, xmax, ymin, ymax)
# coord. ref. : +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0


## display resulting polygons
library(mapview)
m <- mapview(py, color = rainbow(4))
m

polygons

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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