Extracting polygon areas in R

Suppose I have a shapefile (lakes.shp) which consists of 5 polygons (Figure 1a).

lakes = shapefile('lakes.shp')
plot(lakes, col='dodgerblue',main='a) lakes',lty=0)
Figure 1: a) Lake polygons, b) Lake polygons with 30 m buffer
Figure 1: a) Lake polygons, b) Lake polygons with 30 m buffer

The shapefile is stored as a SpatialPolygonsDataFrame. The data underlying these polygons can be viewed with:


There is a column called SHAPE_Area, which is the area of each polygon. Now let’s say, we want to create a buffer zone around the lake (Figure 1b).

lakebuffer = buffer(lakes, width=30, dissolve=F) 
plot(buffer_ring,col='darkred',main = 'b) 30 m buffer',lty=0)

Great! We can still see the underlying data with


However, the SHAPE_Area shown are the original lake areas. To find the true polygon area, we must dig into the polygon layer: buffer_ring@polygons. But each polygon is an element of a list, and the slot with “area” is deeply nested. Instead of looping through each polygon, here’s an easy way to extract polygon areas:

bufAreas = sapply(slot(lakebuffer, "polygons"), slot, "area")

For the area of only the buffer:

lakeAreas = sapply(slot(lakes, "polygons"), slot, "area")
output = data.frame(bufferArea = bufAreas - lakeAreas)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s