r - 合并具有经度和纬度的数据框和形状文件
问题描述
我有一个数据框,其中包含有关犯罪的信息(变量 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 的总和。我正在尝试合并两个数据框,但没有成功。
解决方案
如果您愿意从 -package 切换sp
到sf
-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 链接中的答案。
推荐阅读
- html - 使用 CSS 将动画文本放在背景中?
- function - 如何从单个操作中获得多个输出?
- angular - 如何在下载前预览服务器上的文件?出现错误:不允许加载本地资源:blob
- c++ - C++编译时检查模板类型中是否存在方法
- string - 如何替换批处理文件中字符串中每次出现的=
- c++ - 初始化类对象中的 C++ std::bad alloc 错误
- cloud-foundry - 无服务器计算:Cloud Foundry 的 Diego Elastic Runtime
- ios - 使用 Swift 从 firebase 检索嵌套数据
- r - 颜色代码绘图条按因子填充和边框
- c++ - 为什么在 C++ 中的 for 循环后变量没有更新?