“0.001与纬度/经度坐标相关的约为100m”的假设可能无法保持。距离取决于您所在的世界,但使用您所在地区的示例数据:
library(sf)
adjust latitude by 0.001
df <- data.frame(lat = c(45.123, 45.124), lon = c(-122.789, -122.789))
df.sf <- st_as_sf(df, coords = c(“lon”, “lat”), crs = 4326)
st_distance(df.sf)
Units: m
[,1] [,2]
[1,] 0.0000 111.1342
[2,] 111.1342 0.0000
Or, if we adjust the longitude by 0.001:
df <- data.frame(lat = c(45.123, 45.123), lon = c(-122.789, -122.790))
df.sf <- st_as_sf(df, coords = c(“lon”, “lat”), crs = 4326)
st_distance(df.sf)
Units: m
[,1] [,2]
[1,] 0.00000 78.67796
[2,] 78.67796 0.00000
</code>
以下是使用您的问题的替代解决方案
sf
包:
# add a few more points to make it more interesting
df <- data.frame(id = c(1001, 1002, 1003, 1004, 1005),
lat = c(45.123, 45.123, 45.126, 45.121, 45.130),
lon = c(-122.456, -122.457, -122.444, -122.442, -122.445))
convert to an sf object and set projection (crs) to 4326 (lon/lat)
df.sf <- st_as_sf(df, coords = c(“lon”, “lat”), crs = 4326)
transform to UTM (Zone 10) for distance
df.utm <- st_transform(df.sf, “+proj=utm +zone=10 +datum=WGS84 +units=m +no_defs”)
create a 100m grid on these points
grid.100 <- st_make_grid(x = df.utm, cellsize = c(100, 100))
plot to make sure
library(ggplot2)
ggplot() +
geom_sf(data = df.utm, size = 3) +
geom_sf(data = grid.100, alpha = 0)
</code>
#将grid转换为sf(不是sfc)并添加id列
grid.sf&lt; - st_sf(grid.100)
grid.sf $ id&lt; - 1:nrow(grid.sf)
# find how many points intersect each grid cell by using lengths() to get the number of points that intersect each grid square
grid.sf$count <- st_intersects(grid.sf, df.utm) %>% lengths()
</code>
情节检查
ggplot() +
geom_sf(data = grid.sf, alpha = 0.5, aes(fill = as.factor(count))) +
geom_sf(data = df.utm, size = 3) +
scale_fill_discrete(“Number of Points”)
</code>