首页 > 解决方案 > 在R中查找数据点的某个半径内的点数

问题描述

我有 2 个数据集,一个用于医院,另一个用于程序。每个数据集都有纬度和经度坐标。程序要么在医院内进行,要么在医院外进行,但如果在医院提供,坐标不一定精确。我试图在每个医院周围形成一定大小的半径,并确定平均有多少手术点落在该半径内。因此,例如,如果我有 100 家医院和 3000 个程序,我想在所有医院周围形成一个半径,然后查看平均有多少家医院落入该指定半径内。我的初始代码如下,但我知道这可以更快地完成。用 R 编码。谢谢!

for(i in 1:NROW(hospitals)){
  hospital <- hospitals[i,]
  radius <- .016

  # find all the procedures that lie in the .016 sized radius from this hospital

  hospital$latitude_low <- hospital$lat - radius
  hospital$longitude_low <- hospital$long - radius
  hospital$latitude_high <- hospital$lat + radius
  hospital$longitude_high <- hospital$long + radius

  in_rad <- procedures[(procedures$long >= hospital$longitude_low & procedures$long <= 
  hospital$longitude_high & procedures$lat <= hospital$latitude_high & procedures$lat >= 
  hospital$latitude_low),]

  num <- NROW(in_rad)
  hospitals[i,]$number_of_procedures <- num
}

标签: rgeospatialrastergeosphere

解决方案


当您提出问题时,您应该始终包含一些示例数据。像这样

lat <- c(-23.8, -25.8)
lon <- c(-49.6, -44.6)
hosp <- cbind(lon, lat)


lat <- c(-22.8, -24.8, -29.1, -28, -20)
lon <- c(-46.4, -46.3, -45.3, -40, -30)
procedures <- cbind(lon, lat)

您的数据是经度/纬度吗?如果是这样,您需要使用适当的方法来计算距离。例如

 library(geosphere)
 dm <- distm(procedures, hosp)

或者

 library(raster)
 d <- pointDistance(procedures, hosp, lonlat=TRUE)

两者都计算从所有程序到所有医院的距离。对于非常大的数据集,这将失败,但根据您的描述,它应该可以正常工作。现在您可以使用一个阈值(此处为 400,000 m)来找出哪些程序在每个医院的该距离内

apply(d < 400000, 2, which)
#[[1]]
#[1] 1 2

#[[2]]
#[1] 1 2 3

所以程序 1、2 和 3 都在到医院 2 的距离之内

如果您的数据不是经度/纬度,您可以使用

 d <- pointDistance(procedures, hosp, lonlat=FALSE)

推荐阅读