5

我有一个地图上的点数据框和一个被描述为点多边形的感兴趣区域。我想计算每个点到多边形之间的距离,最好使用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工作的电话?

我在R3.4.1

> packageVersion("dplyr")
[1] ‘0.7.3’
> packageVersion("sf")
[1] ‘0.5.5’
4

1 回答 1

7

所以事实证明,整个混乱是由我的一个小小的愚蠢疏忽造成的。这是细分:

  • points数据框来自与area多边形不同的来源(!)。
  • 监督这一点,我一直试图将它们设置crs 7415为合法但不正确的举动,并最终导致错误的答案。
  • 正确的方法是将它们转换为它们起源的sf对象,将它们转换为对象所在的对象,然后继续计算距离。crsarea

把它们放在一起:

# this part was wrong, crs was supposed to be the one they were
# originally coded in
pnts_sf <- st_as_sf(pnts, crs = 4326L, coords = c("long", "lat"))

# then apply the transformation to another crs
pnts_sf <- st_transform(pnts_sf, crs = 7415L)

st_distance(pnts_sf, area)

--------------------------
Units: m
          [,1]
[1,] 3998.5701
[2,]    0.0000
[3,]  751.8097
于 2017-09-14T18:01:06.077 回答