terra icon indicating copy to clipboard operation
terra copied to clipboard

distance() and expanse() different behaviour with raster/vector

Open AMBarbosa opened this issue 3 months ago • 0 comments

Hi,

distance() requires a CRS for SpatVector, but not for SpatRaster inputs, where instead it computes distance in coordinate units without any warning:

library(terra)
r <- rast(ncols=36, nrows=18, crs="")
r[500] <- 1
p <- vect(rbind(c(0,0), c(90,30), c(-90,-30)))

distance(r)
# no error or warning; output in coordinate units

distance(p)
# Error: [distance] crs not defined

As for expanse(), it doesn't require a CRS in the input object, and it emits is a warning for SpatVector polygons but not for SpatRasters:

expanse(r)
#   layer area
# 1     1  100

expanse(as.polygons(r * 0))
# [1] 100
# Warning message:
# [expanse] unknown CRS. Results can be wrong

I think in all cases it should be like for SpatVector polygons above (as it is also for perim() and buffer()).

I also think it could be useful also to implement the lonlat argument for all input types, as oftentimes we know whether a layer is in degrees or meters, but not the exact CRS.

Cheers!

AMBarbosa avatar Oct 10 '25 19:10 AMBarbosa