# Calculate area for each polygon in R

I am working with a shapefile that has many polygons.

How do I add one more field named "area_sqkm" and calculate area for each polygon in the shapefile?

• What libraries do you have installed and what have you tried? Jun 29, 2016 at 15:57
• rgeos::gArea(x,byid=TRUE) Jun 29, 2016 at 17:21
• Welcome to gis.stackexchange! Please note that a good question on this site is expected to show some degree of research on your part, i.e. what you have tried and - if applicable - code so far. For more info, you can check our faq. Jun 29, 2016 at 19:53

You can do

``````library(raster)
x <- shapefile('file.shp')
crs(x)
x\$area_sqkm <- area(x) / 1000000
``````

Or with `terra`

``````library(terra)
x <- vect('file.shp')
x\$area_sqkm <- expanse(x) / 1000000
``````

That works for both an angular CRS (longitude/latitude) and for planar CRSs. It is generally best to use a longitude/latitude CRS to compute area a planar CRS can distort size with a lot (How much? It depends on the CRS and on the location and extent of your spatial data).

• is `raster::area()` with unprojected data more accurate than `rgeos::gArea()` with projected data? Apr 30, 2019 at 22:45
• It can be. Because projections distort. If the inter-node distance of the polygon is high, projection can distort the area further (see the `geosphere` vignette). May 1, 2019 at 0:14
• For other readers: This returns a numeric vector equal to the number of polygons (it looked to me as if it might be just for one polygon at a time) Aug 27, 2021 at 21:23