Last chance! 50% off unlimited learning
Sale ends in
Compute the area of polygons or for raster cells that are not NA
. Computing the surface area of raster cells is particularly relevant for longitude/latitude rasters, as the size of the cells is constant in degrees, but not in meters. But it can also be very important with raster data if the coordinate reference system is not equal-area. In that case, you can detect variation in true cell size using the correct=TRUE
option.
For vector data, the best way to compute area is to use the longitude/latitude crs if that is what the data come in. This is contrary to (erroneous) popular belief that suggest that you should use a planar coordinate reference system.
The perimeter method works only on SpatVector objects, and computes the length of lines or the perimeter of polygons.
# S4 method for SpatRaster
area(x, sum=TRUE, correct=FALSE, mask=FALSE, filename="", ...)# S4 method for SpatVector
area(x)
# S4 method for SpatVector
perimeter(x)
SpatRaster or SpatVector
logical. If TRUE
the summed area of the cells that are not NA
is returned. Otherwise, a SpatRaster with the area for each cell is returned
logical. If TRUE
, the area is not computed based on the linear units of the coordinate reference system, but on the *actual* area, correcting for distortion. This may be considerably slower. Only relevant for planar coordinate references, not for lon/lat data
logical. If TRUE
, cells that are NA
in x
are also NA
in the output
character. Output filename
additional arguments for writing files as in writeRaster
area or perimeter in m2
# 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