The extent of the raster is equal to the extent of the cell centres, expanded by half the resolution.
Here's an example:
Create a dummy raster with extent c(0, 1, 0, 1)
and resolution c(0.1, 0.1)
:
library(raster)
r <- raster(res=0.1, xmn=0, xmx=1, ymn=0, ymx=1)
Extract cell centres:
p <- rasterToPoints(r)
head(p)
# x y
# [1,] 0.05 0.95
# [2,] 0.15 0.95
# [3,] 0.25 0.95
# [4,] 0.35 0.95
# [5,] 0.45 0.95
# [6,] 0.55 0.95
Calculate the extent of the cell centres:
e <- extent(p)
Expand the extent by half the resolution. Note we don't need to specify 0.5 * res(r)
. The +
method for extent
objects yields a new extent that is res(r)
units longer, overall, on each axis.
e + res(r)
# class : Extent
# xmin : 1.387779e-17
# xmax : 1
# ymin : -5.551115e-17
# ymax : 1
(There's minor floating point error in the recovered extent.)
However, I don't see any problem with your approach, either:
min(p[, 'x']) - xres(r)/2
# [1] 0
max(p[, 'x']) + xres(r)/2
# [1] 1
min(p[, 'y']) - xres(r)/2
# [1] -6.938894e-17
max(p[, 'y']) + yres(r)/2
# [1] 1