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

如何为经纬度数据集添加3英里范围内站点数与单元数统计列?

Solution for Calculating Nearby Sites and Units Within 3 Miles

Here's a complete, efficient approach to add the required columns to your main_df dataframe. We'll use the geosphere package for accurate haversine distance calculations, which is perfect for geographic coordinate data.

Step-by-Step Code

# Load required package
library(geosphere)

# Define 3 miles in meters (1 mile = 1609.344 meters for precise conversion)
three_miles_meters <- 3 * 1609.344

# Calculate distance matrix (rows = sites, columns = distance to other sites in meters)
dist_matrix <- distm(main_df[, c("Lon", "Lat")], fun = distHaversine)

# Create logical matrix where TRUE means sites are within 3 miles
within_3miles <- dist_matrix <= three_miles_meters

# Add "number of sites" column (exclude current site by subtracting 1)
main_df$`number of sites` <- rowSums(within_3miles) - 1

# Add "number of units" column (sum units of nearby sites, exclude current site's units)
main_df$`number of units` <- rowSums(within_3miles * main_df$Units) - main_df$Units

# Reorder columns to match your desired output (optional)
main_df <- main_df[, c("Lat", "Lon", "Units", "number of sites", "number of units")]

Breakdown of the Code

  1. Distance Matrix: distm generates a matrix where each cell [i,j] shows the haversine distance (in meters) between site i and site j. We pass Lon first then Lat because distHaversine expects coordinates in (longitude, latitude) order.
  2. Logical Filter: within_3miles flags all site pairs that are within 3 miles. Each row includes the current site (distance = 0, which counts as within range), so we subtract 1 later to exclude it.
  3. Count Nearby Sites: rowSums(within_3miles) counts all sites (including the current one) in range. Subtract 1 to get the count of other nearby sites.
  4. Sum Nearby Units: Multiply the logical matrix by the Units column to isolate units from only nearby sites, sum each row, then subtract the current site's units to exclude it from the total.
  5. Column Reordering: Optional step to match the exact column order from your example output.

Example Match

Using your sample data, this code will produce exactly the results you showed. For example:

  • The row with Lat=39.67114, Lon=-86.07211 has no nearby sites, so number of sites=0 and number of units=0.
  • The row with Lat=40.06127, Lon=-86.05604 has 2 nearby sites, summing to 184 units (184 = total of other sites' units, excluding its own 80).

Quick Notes

  • Ensure your Lat and Lon columns are numeric (not character) before running this code.
  • For 1000 rows, this runs efficiently—1000x1000 matrices are easily handled in R's memory.

内容的提问来源于stack exchange,提问作者J. Shields

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:52:24