简体   繁体   English

`terra` 中的 `sp::over()` 等价物

[英]`sp::over()` equivalent in `terra`

Is there an equivalent of sp::over() in package terra ? package terra中是否有等效的sp::over() To get a data frame showing which geometries of a SpatVector overlay which geometries of another SpatVector -- like this, but using only terra :要获取显示 SpatVector 的哪些几何图形覆盖另一个 SpatVector 的哪些几何图形的数据框 - 像这样,但仅使用terra

# get a polygons map:
library(terra)
lux <- vect(system.file("ex/lux.shp", package="terra"))
plot(lux)
text(lux, lux$NAME_2)

# get points that overlay some of those polygons:
pts <- vect(cbind(c(5.8, 6, 6.2), c(49.85, 49.5, 49.6)), crs = crs(lux))
plot(pts, col = "blue", add = TRUE)

# find which points overlay which polygons:
library(sp); library(raster)
over(as(pts, "Spatial"), as(lux, "Spatial"))

#   ID_1     NAME_1 ID_2           NAME_2 AREA    POP
# 1    1   Diekirch    3          Redange  259  18664
# 2    3 Luxembourg    9 Esch-sur-Alzette  251 176820
# 3    3 Luxembourg   10       Luxembourg  237 182607

在此处输入图像描述

Your example data您的示例数据

library(terra)
lux <- vect(system.file("ex/lux.shp", package="terra"))
pts <- vect(cbind(c(5.8, 6, 6.2), c(49.85, 49.5, 49.6)), crs = crs(lux))

You can use extract (also in raster )您可以使用extract (也在raster

extract(lux, pts)[,-1]
#  ID_1     NAME_1 ID_2           NAME_2 AREA    POP
#1    1   Diekirch    3          Redange  259  18664
#2    3 Luxembourg    9 Esch-sur-Alzette  251 176820
#3    3 Luxembourg   10       Luxembourg  237 182607

Or you can do (a variation on the solution by lovalery)或者你可以这样做(由lovalery对解决方案的一种变体)

i <- relate(pts, lux, "within") |> apply(2, any)
lux[i,] |> data.frame()
#  ID_1     NAME_1 ID_2           NAME_2 AREA    POP
#1    1   Diekirch    3          Redange  259  18664
#2    3 Luxembourg    9 Esch-sur-Alzette  251 176820
#3    3 Luxembourg   10       Luxembourg  237 182607

Or simply like this或者只是像这样

i <- is.related(lux, pts, "intersects")
lux[i,] |> data.frame()
#  ID_1     NAME_1 ID_2           NAME_2 AREA    POP
#1    1   Diekirch    3          Redange  259  18664
#2    3 Luxembourg    9 Esch-sur-Alzette  251 176820
#3    3 Luxembourg   10       Luxembourg  237 182607

Please find below one possible solution using the terra library请使用terra库在下面找到一种可能的解决方案

Reprex代表

  • Code代码
library(terra)

values(lux)[apply(terra::relate(lux, pts, "covers"), 2, function(x) which(x == TRUE)),]
  • Output Output
#>    ID_1     NAME_1 ID_2           NAME_2 AREA    POP
#> 3     1   Diekirch    3          Redange  259  18664
#> 10    3 Luxembourg    9 Esch-sur-Alzette  251 176820
#> 11    3 Luxembourg   10       Luxembourg  237 182607

Created on 2022-01-17 by the reprex package (v2.0.1)代表 package (v2.0.1) 于 2022 年 1 月 17 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM