Skip to content

Instantly share code, notes, and snippets.

@dbaston
Created April 17, 2018 17:15
Show Gist options
  • Save dbaston/767e9a2d7f2e4c20c6ea1305a7351c5e to your computer and use it in GitHub Desktop.
Save dbaston/767e9a2d7f2e4c20c6ea1305a7351c5e to your computer and use it in GitHub Desktop.
Find a common extent for two rasters whose grids should align but don't because of rounding errors
require(raster)
# round resolution to nearest arc second
snap_res <- function(r) {
round(res(r)*3600)/3600
}
# make sure extent fits cleanly onto a grid
# having its origin at -180, -90
snap_extent <- function(r) {
origin <- c(-180, -90)
ll <- origin - round((origin - extent(r)[c(1, 3)])/res(r))*res(r)
ur <- ll + res(r)*dim(r)[c(2, 1)]
raster::extent(c(ll[1], ur[1], ll[2], ur[2]))
}
footprint <- raster('footprint.tif')
yield <- raster('yield.tif')
res(footprint) <- snap_res(footprint)
res(yield) <- snap_res(yield)
stopifnot(res(footprint) == res(yield))
extent(footprint) <- snap_extent(footprint)
extent(yield) <- snap_extent(yield)
combined_extent <- merge(extent(footprint), extent(yield))
footprint <- extend(footprint, combined_extent)
yield <- extend(yield, combined_extent)
stk <- stack(footprint, yield)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment