簡體   English   中英

是在 R 中使用 sf 的 MULTIPOLYGON 中的一個點

[英]Is a POINT within a MULTIPOLYGON using sf in R

我有一個數據框( addresses ),其中包含 6 個位置的緯度/經度信息。 我還添加了(出於說明目的)該位置實際所屬的國家/地區(我的真實數據中沒有這個)。 然后我使用st_as_sf函數將此數據幀轉換為 sf 對象( addresses_sf )。

然后,我通過獲得加拿大邊境的SF對象rnaturalearth包,它保存為can

我想確定address_sf中的哪些條目在加拿大,所以我使用 sf 包中的st_intersection函數。

不幸的是,當它運行時,它只將第二個條目 (45.41126, -75.70591) 識別為在加拿大邊界內,而無法識別結果中的其余 3 個條目。

我在下面附上了一些可重現的代碼,希望它可以確定我做錯了什么......

## Load necessary libraries
library(tidyverse)
library(rnaturalearth)
library(sf)

## Create data
addresses <- tibble::tribble(
                   ~lat,      ~lon, ~country,
               43.77264,  -88.4462,    "usa",
               45.41126, -75.70591, "canada",
                 42.235, -83.06181, "canada",
               45.38441, -70.84368, "canada",
               42.11125,  -83.1107, "canada",
               44.74441, -74.86597,    "usa"
               )

## Convert to sf
addresses_sf <- addresses %>% 
  rowid_to_column() %>% 
  st_as_sf(coords = c("lon", "lat"), crs = 4326)
  
## Get Canadian borders
can <- rnaturalearth::ne_countries(country = "Canada", returnclass = "sf") %>% 
  select(name) %>% 
  st_transform(crs = 4326)

## Determine which entries are in Canada
sf::st_intersection(addresses_sf, can)

更新:

感謝@Ray 將上述腳本中的錯誤突出顯示為沒有足夠的分辨率。 我用下面的行更新了對 rnaturalearth 的調用,代碼現在按預期運行。

## Get Canadian borders
can <- rnaturalearth::ne_countries(country = "Canada", scale = "large", returnclass = "sf") %>% 
   select(name) %>% 
   st_transform(crs = 4326)

@Tony Machado,您在這里遇到了解決問題。 來自自然地球的多邊形(即加拿大)的邊界線的分辨率可能會切斷邊界線。 如果您繪制手頭的問題,您會看到一些城市靠近邊界。

library(ggplot2)
ggplot() + 
  geom_sf(data = can, fill = "lightblue") + 
  geom_sf(data = addresses_sf, color = "red", size = 2)

在此處輸入圖片說明

你可以

  • 獲得更高分辨率的邊界(例如,在您的ne_countries()調用中添加一個scale = "large" ); 或工作
  • 帶緩沖區。

對於緩沖,可能值得將 WGS84 重新投影到 UTM 並使用更精細的距離測量。 在 WGS84 中, dist以弧度為單位。 那會很痛苦。 但是從下面,您可以看到當我們緩沖加拿大邊界時,您增加了includes 不幸的是,這也抓住了“底特律”:(

希望這能讓你繼續前進。

sf::st_intersection(addresses_sf, st_buffer(can, dist = 0.001))
Simple feature collection with 5 features and 3 fields
Geometry type: POINT
Dimension:     XY
Bounding box:  xmin: -83.1107 ymin: 42.11125 xmax: -70.84368 ymax: 45.41126
Geodetic CRS:  WGS 84
# A tibble: 5 x 4
  rowid country name               geometry
* <int> <chr>   <chr>           <POINT [°]>
1     2 canada  Canada (-75.70591 45.41126)
2     3 canada  Canada   (-83.06181 42.235)
3     4 canada  Canada (-70.84368 45.38441)
4     5 canada  Canada  (-83.1107 42.11125)
5     6 usa     Canada (-74.86597 44.74441)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM