0

I am working on a project where I pull crime data from an API, and essentially calculate the density of crime per predefined grid unit. I do this now by putting lat and lon into a data.frame and then calculating the count of points within a radius of a point center. This is computationally expensive as there are thousands of points in the predefined grid and thousands of crime points.

I'm wondering if there is a better way to calculate crime density; I've heard that raster may be valuable?

Some sample data:

# Create a predefined grid of coordinates
predef.grid <- data.frame(lat = seq(from = 2.0, to = 4.0, by = 0.1),lon = seq(from = 19.0, to = 21.0, by = 0.1))
predef.grid <- expand.grid(predef.grid)

# Create random sample of crime incidents
crime.incidents <- data.frame(lat = rnorm(10, 4),lon = rnorm(10,20))
crime.incidents <- expand.grid(mydata)

# Need to count number of crimes within radius of every point in predef.grid

Thanks!

4

1 回答 1

0
# Need to count number of crimes within radius of every point in   
library(raster)
library(sp)

# predfined raster
predef.grid <- raster(xmn=2,  # xmin
                  ymn=4,  # ymin
                  xmx=19, # xmax
                  ymx=21, # ymax
                  res=1,  # spatial resolution
                  vals = 1) # cell value
plot(predef.grid)

# Create random sample of crime incidents
# points should be a Spatial object of some form, point, etc.
crime.incidents <- spsample(x = as(extent(predef.grid), 'SpatialPolygons'),
                        n =  100, 
                        type = 'random')

# plot points over grid
points(crime.incidents, pch = 20)

# count points per cell
density <- rasterize(crime.incidents, predef.grid, fun='count')

# plot the density 
plot(density)

在此处输入图像描述

在此处输入图像描述

于 2018-08-03T23:48:10.197 回答