Useful R code

From Intamap

This page contains nice R functions that people from the intamap project have written and could be useful for other project members. Post your code in a new chapter and use one space indendation to make the code also have the format for code. Please explain all the inputs and outputs carefully. Always try to add a small piece of code that uses your function. Make sure that the datasets you use for this are generally available in R. An example of this is the meuse dataset in the gstat package. It is also wise to mention your name so people know who they can ask questions if they have problems.

Create SpatialPolygons object from bounding box of spatial object

Contributed by Paul Hiemstra

bbox2polygon = function(obj) {
# This function converts a bounding box of a spatial object to a SpatialPolygons-object
# obj :  Spatial object
  bb = bbox(obj)
  pl = Polygon(data.frame(rbind(c(bb["x","min"], bb["y","max"]),
                                c(bb["x","max"], bb["y","max"]),
                                c(bb["x","max"], bb["y","min"]),
                                c(bb["x","min"], bb["y","min"]),
                                c(bb["x","min"], bb["y","max"])
                            )))
  pls = Polygons(list(pl), ID = "bbox")
  spat_poly = SpatialPolygons(list(pls), proj4string = CRS(proj4string(obj)))
  return(spat_poly)
}

data(meuse)
coordinates(meuse) = ~x+y

pl = bbox2polygon(meuse)
plot(pl)
points(meuse)