[GIS] Creating a map of population density using shapefiles in R

r

This would be a pretty simple task for me in ArcGIS, but I'm trying to start using R and I'm stumped. I have census data in the form of a shapefile that contains the population of each shape in the shapefile. I would like to divide the population by the area of each shape in order to create a density map. But I can't figure out how to calculate the area of each shape in the shapefile, and I can't figure out how to take the area once I've calculated it and divide the population by the area.

Best Answer

library(rgdal)
library(raster)

areashp<-readOGR("C:/","Census")
areashp$Totalarea<-area(areashp)
areashp$density<- areashp$population / areashp$Totalarea

Also make sure you are in UTM or another projection for calculating area

Using rgeos:

library(rgeos)
areashp$Totalarea<-gArea(areashp, byid=TRUE)
areashp$density<- areashp$population / areashp$Totalarea

Alternatively, as per Jeffrey's comment you could use: areashp$density<- areashp$population / rgeos::gArea(areashp, byid=TRUE) if you don't want area in your attribute table.