2

I'm looping through a list of rasters, getting the bounding box for each from raster@extent, and storing the matrices representing each polygon in a list. I'd ultimately like to save to shapefile where there will be like 359 polygons like: enter image description here

I'm having trouble understanding how to actually get these polygons into a form that they can be exported as a shapefile. I have tried, for instance:

for (i in 1:length(file_list)){
    
    im <- raster(file_list[i])
    min_x <- im@extent@xmin
    max_y <- im@extent@ymax
    max_x <- im@extent@xmax
    min_y <- im@extent@ymin
    
    x_coord <- c(min_x, max_x, max_x, min_x, min_x)
    y_coord <- c(max_y, max_y, min_y, min_y, max_y)
    xy_mat <- cbind(x_coord, y_coord)
    poly_list <- rbind(poly_list, list(xy_mat))
    
  }

  #create simple feature polygon
  poly_sf <- st_polygon(poly_list)

I'm unclear on where to go from here. Admittedly I'm not an R spatial ninja but I thought there would be a relatively straightforward way to get from coordinates representing polygons to a shapefile. I am able to add extent and CRS whenever that is called for. I'm not wed to sf, that's just the furthest I got.

1 Answer 1

4

You can get a polygon from a raster extent by wrapping st_bbox in st_as_sfc. The following snippet will loop over files and write a GeoPackage with the file name and polygon extent of each raster:

file_list <- Sys.glob('/home/dan/data/*.tif')

polys <- do.call(rbind, lapply(file_list, function(fname) {
  st_sf(
    source = fname,
    geometry = st_as_sfc(st_bbox(raster(fname)))    
  )
}))

st_write(polys, '/tmp/polys.gpkg')
0

Your Answer

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

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