I have two data sets, one for crime in Chicago, labeled with longitude and latitude coords and a shapefile of census blocks also in Chicago. Is it possible in R to aggregate crimes within census blocks, given these two files? The purpose is to be able to map out the crimes by census block.
Location for download of Chicago census tract data: https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-Census-Blocks-2000/uktd-fzhd
Location for download of crime data: https://data.cityofchicago.org/Public-Safety/Crimes-2001-to-present/ijzp-q8t2
Some code that I have pruned down from another project. When it is through there is a spatial object for census tract information and a dataframe containing crime data, including lon/lat coords:
library(rgdal)
library(dplyr)
#Helper function to reduce crime data to single year and limit to variables of interest
yearReduce <- function(rawData=NULL,year=NULL) {
datout <- data.frame(year = numeric(0), community = numeric(0), type = numeric(0), arrest = numeric(0),
Latitude = numeric(0), longitude = numeric(0))
dat <- rawData[rawData$Year==year,]
datout <- data.frame(year = dat$Year, community = as.numeric(dat$Community.Area), type = dat$Primary.Type, arrest = dat$Arrest,
latitude = dat$Latitude, longitude = dat$Longitude)
datout
}
#Load crime data
crimedata <- '~/Documents/data/Crimes_-_2001_to_present.csv'
mydata_crime <- read.csv(crimedata,na.strings = c("", " ", "NA"), stringsAsFactors=F)
mydata_crime$Primary.Type <- tolower(mydata_crime$Primary.Type)
#Set cwd to location of the census tract shape file
setwd('~/Documents/data/Boundaries_-_Census_Blocks_-_2010/')
#Create spatial vector object and transform projection
tract = readOGR(".","CensusBlockTIGER2010") %>% spTransform(CRS("+proj=longlat +datum=WGS84"))
### Process crime data to narrow to single year###
crime2010 <- yearReduce(mydata_crime,'2010')
# further select specific crime(s). Fairly limited for testing purposes
violent_crimes <- subset(crime2010,
type == "homicide")
violent_crimes <- violent_crimes[complete.cases(violent_crimes),] #Clean data a little bit
Thank you for any help you may be able to provide.
Patrick