# NOT RUN {
### SpatRaster
r <- rast(nrow=18, ncol=36)
v <- 1:ncell(r)
v[200:400] <- NA
values(r) <- v
# area for each raster cell
a <- area(r, sum=FALSE)
# summed area in km2
area(r) / 1000000
## you can use mask to remove the cells in r that are NA
## and compute the global sum to get the same result
am <- mask(a, r)
global(am, "sum", na.rm=TRUE) / 1000000
# effect of "correct" (commented out as this does not work with old GDAL)
#r <- rast(ncol=90, nrow=45, ymin=-80, ymax=80)
#m <- project(r, "+proj=merc")
#a <- area(m, sum=FALSE, names="naive")
#b <- area(m, correct=TRUE, sum=FALSE, names="corrected")
#plot(c(a, b)/1000000, nc=1)
### SpatVector
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
a <- area(v)
a
sum(a)
perimeter(v)
# }
Run the code above in your browser using DataLab