You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R语言sf包判断人员是否位于城市5公里范围内

使用sf包判断人员是否在城市5公里范围内

需求:用sf包判断哪些people位于任意cities的5公里范围内。示例中,人员1和2分别处于Raleigh、Greensboro的5公里范围内,应返回"Yes";人员3不在任何城市的5公里范围内,返回"No"。

原始数据代码

library(tidyverse)
library(sf)

cities <- data.frame(city = c("Raleigh", "Greensboro", "Wilmington"),
                     x = c(-78.633333, -79.819444, -77.912222),
                     y = c(35.766667, 36.08, 34.223333)) %>% 
  st_as_sf(coords = c("x", "y"), crs = 4326) %>% 
  st_transform(2264) 

people <- data.frame(person = c(1:3),
                     x = c(-78.634899, -79.821140, -103.236804),
                     y = c(35.766266, 36.077911, 30.551109)) %>% 
  st_as_sf(coords = c("x", "y"), crs = 4326) %>% 
  st_transform(2264) 

方案1:输出每个人是否在任意城市范围内

先计算人员与所有城市的距离,再判断是否存在距离小于5公里(注:CRS 2264单位为英尺,5公里≈16404英尺)的情况:

people %>%
  mutate(
    insideRad = if_else(
      st_distance(people, cities) %>% as.numeric() %>% apply(1, min) < 16404,
      "Yes", "No"
    )
  ) %>%
  st_drop_geometry() %>%
  select(person, insideRad)

输出结果:

# A tibble: 3 × 2
  person insideRad
   <dbl> <chr>    
1      1 Yes      
2      2 Yes      
3      3 No   

方案2:输出每个人对应每个城市的判断结果

先将人员和城市做全连接,再计算每个组合的距离并判断:

crossing(people, cities) %>%
  mutate(
    distance = st_distance(geometry.x, geometry.y) %>% as.numeric(),
    insideRad = if_else(distance < 16404, "Yes", "No")
  ) %>%
  st_drop_geometry() %>%
  select(person, city, insideRad)

输出结果:

# A tibble: 9 × 3
  person city       insideRad
   <dbl> <chr>      <chr>    
1      1 Raleigh    Yes      
2      1 Greensboro No       
3      1 Wilmington No       
4      2 Raleigh    No       
5      2 Greensboro Yes      
6      2 Wilmington No       
7      3 Raleigh    No       
8      3 Greensboro No       
9      3 Wilmington No       

内容的提问来源于stack exchange,提问作者Eric Green

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:42:33