在 R 中使用 terra 包指向多边形

point in polygon using terra package in R

我想使用 terra 包在多边形分析中做一个点。我有一组点,我想提取它们属于哪些多边形。下面的示例数据显示了单个多边形

library(terra)
crdref <- "+proj=longlat +datum=WGS84"
  
longitude <- c(-116.7, -120.4, -116.7, -113.5, -115.5, -120.8, -119.5, -113.7, -113.7, -110.7)
latitude <- c(45.3, 42.6, 38.9, 42.1, 35.7, 38.9, 36.2, 39, 41.6, 36.9)
lonlat <- cbind(longitude, latitude)
pts <- vect(lonlat, crs=crdref)
  
lon <- c(-116.8, -114.2, -112.9, -111.9, -114.2, -115.4, -117.7)
lat <- c(41.3, 42.9, 42.4, 39.8, 37.6, 38.3, 37.6)
lonlat <- cbind(id=1, part=1, lon, lat)
pols <- vect(lonlat, type="polygons", crs=crdref)
  
plot(pols, border='blue', col='yellow', lwd=3)
points(pts, col='red', pch=20, cex=3)

terra::extract(pts, pols)
       id.y id.x
[1,]    1   NA

但我不清楚输出结果。我只需要每个点落入哪个多边形。

我想你正在寻找 terra::intersect

points(intersect(pols, pts), col = 'blue')

有一个 relate 函数允许将“包含”指定为所需的关系:

relate(pols, pts, "contains")
      [,1]  [,2] [,3] [,4]  [,5]  [,6]  [,7] [,8] [,9] [,10]
[1,] FALSE FALSE TRUE TRUE FALSE FALSE FALSE TRUE TRUE FALSE

示例数据

library(terra)
longitude <- c(-116.7, -120.4, -116.7, -113.5, -115.5, -120.8, -119.5, -113.7, -113.7, -110.7)
latitude <- c(45.3, 42.6, 38.9, 42.1, 35.7, 38.9, 36.2, 39, 41.6, 36.9)
pts <- vect(cbind(longitude, latitude), crs="+proj=longlat")
  
lon <- c(-116.8, -114.2, -112.9, -111.9, -114.2, -115.4, -117.7)
lat <- c(41.3, 42.9, 42.4, 39.8, 37.6, 38.3, 37.6)
lonlat <- cbind(id=1, part=1, lon, lat)
pols <- vect(lonlat, type="polygons", crs="+proj=longlat")

这里有四种方法

## 1
e <- extract(pols, pts) 
e[!is.na(e[,2]), 1]
#[1] 3 4 8 9
 
## 2
relate(pols, pts, "contains") |> which()
#[1] 3 4 8 9

## 3 
is.related(pts, pols, "intersects") |> which()
#[1] 3 4 8 9

## 4
pts$id <- 1:nrow(pts)
intersect(pts, pols)$id 
#[1] 3 4 8 9

所以你在 extract 的轨道上是正确的,但你的参数顺序错误。如果您有多个多边形,extract 可能是最简单的。

更多示例