[R-sig-Geo] converting bounding box to shapefile problem

Robert Hijmans r.hijmans at gmail.com
Sat Jun 11 06:57:15 CEST 2011


Interesting problem

> You have to decide if you want to create 7 different shapefiles, one 
> for each of your grids and each containing one bounding box polygon, 
> or one shapefile with 7 features. 

Here is a solution, I think, if you want a single shapefile with all
bounding boxes

library(raster)
maps <- list.files(, ".asc", full.names=TRUE)

# get extents. Advantage of this no need to read the raster file values
ext <- lapply(maps, function(x)  extent(raster(x)))

# get SpatialPolygons (is there an easier way to append SpatialPolygons with
the same ID?)
sp <- SpatialPolygons(lapply(1:length(ext), function(x) { Polygons(list(
as(ext[[x]], 'SpatialPolygons')@polygons[[1]]@Polygons[[1]]), x) } ))

# data.frame
dat <- do.call(rbind, lapply(ext, function(x)  as.vector(bbox(x))))
dat <- data.frame(dat, filename=basename(maps))
colnames(dat)[1:4] = c('xmin', 'ymin', 'xmax', 'ymax')

sp <- SpatialPolygonsDataFrame(sp, dat)

writeOGR(sp, ".", layer='filename', driver="ESRI Shapefile")

plot(sp)
xy = coordinates(sp)
text(xy[,1], xy[,2], 1:nrow(xy))


--
View this message in context: http://r-sig-geo.2731867.n2.nabble.com/converting-bounding-box-to-shapefile-problem-tp6462495p6464586.html
Sent from the R-sig-geo mailing list archive at Nabble.com.



More information about the R-sig-Geo mailing list