我有一个地图上的点数据框和一个被描述为点多边形的感兴趣区域。我想计算每个点到多边形之间的距离,最好使用sf
包。
library("tidyverse")
library("sf")
# area of interest
area <-
"POLYGON ((121863.900623145 486546.136633659, 121830.369032584 486624.24942906, 121742.202408334 486680.476675484, 121626.493982203 486692.384434804, 121415.359596921 486693.816446951, 121116.219703244 486773.748535465, 120965.69439283 486674.642759986, 121168.798757601 486495.217550029, 121542.879304342 486414.780364836, 121870.487595417 486512.71203006, 121863.900623145 486546.136633659))"
# convert to sf and project on a projected coord system
area <- st_as_sfc(area, crs = 7415L)
# points with long/lat coords
pnts <-
data.frame(
id = 1:3,
long = c(4.85558, 4.89904, 4.91073),
lat = c(52.39707, 52.36612, 52.36255)
)
# convert to sf with the same crs
pnts_sf <- st_as_sf(pnts, crs = 7415L, coords = c("long", "lat"))
# check if crs are equal
all.equal(st_crs(pnts_sf),st_crs(area))
我想知道为什么以下方法没有给我正确的答案。
1.单纯用fun-st_distance
不起作用,错误的答案
st_distance(pnts_sf, area)
2.在变异调用中 - 所有错误的答案
pnts_sf %>%
mutate(
distance = st_distance(area, by_element = TRUE),
distance2 = st_distance(area, by_element = FALSE),
distance3 = st_distance(geometry, area, by_element = TRUE)
)
然而,这种方法似乎有效并给出了正确的距离。
3.map
在长/纬度 - 正常工作
pnts_geoms <-
map2(
pnts$long,
pnts$lat,
~ st_sfc(st_point(c(.x, .y)) , crs = 4326L)
) %>%
map(st_transform, crs = 7415L)
map_dbl(pnts_geoms, st_distance, y = area)
我是空间数据的新手,我正在尝试学习这个sf
包,所以我想知道这里出了什么问题。据我所知,前两种方法最终以某种方式最终考虑了“作为一个整体”的点(其中一个点在区域多边形内,所以我想这就是为什么错误答案之一是 0)。第三种方法是一次考虑一个点,这是我的意图。
任何想法我怎样才能得到mutate
工作的电话?
我在R
3.4.1
> packageVersion("dplyr")
[1] ‘0.7.3’
> packageVersion("sf")
[1] ‘0.5.5’