0

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.

  • Do you know how to read a shapefile into an R object? – Spacedman Mar 29 '18 at 17:52
  • @Spacedman yes! I also know how to map it, etc, I just can't figure out how to calculate the area and manipulate the fields. – Help Mar 29 '18 at 17:53
  • Show us some code - you could be using sp or sf spatial data in R. You don't use shapefiles in R, you read them into spatial objects. – Spacedman Mar 29 '18 at 21:28
1
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.

  • 2
    Why add a spurious "area" column to the data and import an entire package into the namespace when you only need one function? Just use: areashp$density<- areashp$population / rgeos::gArea(areashp, byid=TRUE) – Jeffrey Evans Mar 29 '18 at 20:12
  • Personal preference? I come from Arc where the geometries are in the attribute table already. ¯_(ツ)_/¯ – GISKid Mar 29 '18 at 21:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.