首页 > 解决方案 > 合并具有经度和纬度的数据框和形状文件

问题描述

我有一个数据框,其中包含有关犯罪的信息(变量 x),以及犯罪发生地点的纬度和经度。我有一个来自圣保罗市的地区的形状文件。我需要合并这两个数据,这样我就可以获得每个地区的 os 犯罪数量。有没有办法做到这一点?我使用空间数据框转换了我的数据框

df.sp <- SpatialPointsDataFrame(cbind(df$longitude,df$latitude ), df)

但我不知道如何实现这种合并来获得我需要的东西。在 df 我有超过 10,000 个 obs,例如:

    latitude  longitude  n_homdol
1    -23.6     -46.6     1
2    -23.6     -46.6     1
3    -23.6     -46.6     1
4    -23.6     -46.6     1
5    -23.6     -46.6     1
6    -23.6     -46.6     1

形状文件如下:

                       geometry      NOME_DIST
1 POLYGON ((352436.9 7394174,... JOSE BONIFACIO
2 POLYGON ((320696.6 7383620,...    JD SAO LUIS
3 POLYGON ((349461.3 7397765,...    ARTUR ALVIM
4 POLYGON ((320731.1 7400615,...        JAGUARA
5 POLYGON ((338651 7392203, 3...  VILA PRUDENTE
6 POLYGON ((320606.2 7394439,...        JAGUARE

我需要按地区计算 n_homdol 的总和。我正在尝试合并两个数据框,但没有成功。

标签: rshapefilesp

解决方案


如果您愿意从 -package 切换spsf-package,您将有一种简单的方法来使用dplyr-like 语法进行空间连接。: st_join.

它会像这样工作(我在这台电脑上没有 R,所以可能会有一些“笔误”)


library(sf)
library(dplyr)

#Instead of data.frame of class "sp", create "simple features"-data.frame 

sf_df = st_as_sf(df, coords = c("longitude", "latitude"), crs = 4326)

#You'll have to convert your shapefile to sf, too. 
#Depending what class it is you can use "st_as_sf()"


#Then join the shapefile with sf_df via the "st_contains" which merges two rows 
#if a point from sf_df falls within a polygon from the shapefile.

shape_df <- st_join(shapefile, sf_df , join = st_contains)

然后你可以这样做:

shape_df %>%
group_by(NOME_DIST) %>%
summarise(crime = sum(n_homdol))

如果您想坚持下去,sp我建议您查看评论中 Dave2e 链接中的答案。


推荐阅读