Return cell size of a SpatRaster or stars object
st_cell_size(x, warn = TRUE, drop_units = FALSE)A single numeric value representing the cell size of input x
equivalent to the product of the input's x and y raster resolution. By default
and if x has projected coordinates, the cell size is returned with
the units according to input x's CRS.
library(terra)
library(sf)
# a raster with projected coordinates
r_projected <- rast(
nrows = 10, ncols = 10, xmin = 0, xmax = 100, ymin = 0, ymax = 100,
crs = "EPSG:2026"
)
values(r_projected) <- sample(5, ncell(r_projected), replace = TRUE)
# plot(r_projected)
# units of projected coordinates
st_crs(r_projected)$units
#> [1] "m"
# pixel resolution of raster
res(r_projected)
#> [1] 10 10
# cell size of raster-pixel
st_cell_size(r_projected)
#> 100 [m^2]
# cell size without units
st_cell_size(r_projected, drop_units = TRUE)
#> [1] 100
# a raster with geographic coordinates
r_geographic <- rast(
nrows = 10, ncols = 10, xmin = 0, xmax = 100, ymin = 0, ymax = 100,
crs = "EPSG:4326"
)
values(r_geographic) <- sample(5, ncell(r_geographic), replace = TRUE)
# plot(r_geographic)
# unavailable units of geographic coordinates
st_crs(r_geographic)$units
#> NULL
# pixel resolution of raster
res(r_geographic)
#> [1] 10 10
# if raster has geographic coordinates
# cell size is return by default without units and with a warning
st_cell_size(r_geographic)
#> Warning: x has geographic coordinates, thus raster cell size is returned without units
#> [1] 100
# warning can be avoided
st_cell_size(r_geographic, warn = FALSE)
#> [1] 100