Skip to content

Instantly share code, notes, and snippets.

@mdsumner
Created February 19, 2025 10:14
Show Gist options
  • Save mdsumner/b9274658442ebe6c1f8e996f5e673a83 to your computer and use it in GitHub Desktop.
Save mdsumner/b9274658442ebe6c1f8e996f5e673a83 to your computer and use it in GitHub Desktop.
cellcentre.offset <- function(x) {
  ex <- terra::ext(x)
  res <- terra::res(x)
  halfcell <- res/2
  cco <- c(ex[1], ex[4]) + halfcell * c(1, -1)
  cco
}

library(terra)

 f <- system.file("ex/elev.tif", package="terra")

r <- rast(f)

## this is just the xmin/ymax push into the centre of the pixel     
cellcentre.offset(r)

## note that res() is x/y but dim() is y/x (try reading ?GridTopology you have to figure it out by trial/error)
GT <- sp::GridTopology(cellcentre.offset(r), terra::res(r), dim(r)[2:1])

spgdf <- sp::SpatialGridDataFrame(GT, data.frame(values = terra::values(r)[, 1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment