如何计算犯罪密度?

时间:2018-08-06 14:08:15

标签: r gis geospatial sp sf

总体目标:计算美国城市的网格结构中的犯罪密度。每个网格正方形应为100米见方。我有一个数据框 crime.inc ,其中列出了个别犯罪案例lat和lon;像这样的东西:

incident id   lat       lon
1001         45.123   -122.456
1002         45.456   -122.789

接下来,我有一个预定义的网格 g ,这是一个常规网格

predef.grid <- data.frame(lat = seq(from = 44, to = 45, by = 0.1),lon = seq(from = -122, to = -121, by = 0.1))
id <- rownames(predef.grid)  # add row ids
predef.grid <- cbind(id=id, predef.grid)  # add row ids

我的输出必须是这样的,每一行都是预定义网格中的唯一网格,计数是该网格内的事件数:

id      lat   lon       count
1001  45.123  -122.789    4
1002  45.456  -122.987    5

我尝试过以各种形式使用sp,sf,raster和rgeos,但从来没有让岩石越过山丘!任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

“与纬度/经度坐标相关的0.001大约= 100m”的假设可能无法成立。距离将取决于您在世界上的哪个位置,但将使用您所在地区的示例数据:

library(sf)

# adjust latitude by 0.001
df <- data.frame(lat = c(45.123, 45.124),  lon = c(-122.789, -122.789))
df.sf <- st_as_sf(df, coords = c("lon", "lat"), crs = 4326)
> st_distance(df.sf)
Units: m
         [,1]     [,2]
[1,]   0.0000 111.1342
[2,] 111.1342   0.0000

#Or, if we adjust the longitude by 0.001:
df <- data.frame(lat = c(45.123, 45.123),  lon = c(-122.789, -122.790))
df.sf <- st_as_sf(df, coords = c("lon", "lat"), crs = 4326)
> st_distance(df.sf)
Units: m
         [,1]     [,2]
[1,]  0.00000 78.67796
[2,] 78.67796  0.00000

以下是使用sf软件包来解决您的问题的替代解决方案:

# add a few more points to make it more interesting
df <- data.frame(id = c(1001, 1002, 1003, 1004, 1005),
                 lat = c(45.123, 45.123, 45.126, 45.121, 45.130), 
                 lon = c(-122.456, -122.457, -122.444, -122.442, -122.445))

# convert to an sf object and set projection (crs) to 4326 (lon/lat)
df.sf <- st_as_sf(df, coords = c("lon", "lat"), crs = 4326)

# transform to UTM (Zone 10) for distance
df.utm <- st_transform(df.sf, "+proj=utm +zone=10 +datum=WGS84 +units=m +no_defs")

# create a 100m grid on these points
grid.100 <- st_make_grid(x = df.utm, cellsize = c(100, 100))

# plot to make sure
library(ggplot2)
ggplot() +
  geom_sf(data = df.utm, size = 3) +
  geom_sf(data = grid.100, alpha = 0)

enter image description here     #将网格转换为sf(非sfc)并添加一个id列     grid.sf <-st_sf(grid.100)     grid.sf $ id <-1:nrow(grid.sf)

# find how many points intersect each grid cell by using lengths() to get the number of points that intersect each grid square
grid.sf$count <- st_intersects(grid.sf, df.utm) %>% lengths()

要检查的图

ggplot() +
  geom_sf(data = grid.sf, alpha = 0.5, aes(fill = as.factor(count))) +
  geom_sf(data = df.utm, size = 3) +
  scale_fill_discrete("Number of Points")

enter image description here

答案 1 :(得分:0)

对于问题数据的暗示,纬度和经度只有三个小数。因此,您只需使用dplyr即可按位置分组,而无需使用GIS软件包。

library(dplyr)
densities <- crime.inc %>% group_by(lat,lon) %>% 
             summarise(count=n())

这样,您将丢失ID。如果您想保留ID

library(dplyr)
densities <- crime.inc %>% group_by(lat,lon) %>% 
             rename(count=n())