r - `sp::over()` 相当于 `terra`

标签 r spatial terra

terra 中是否有等价于 sp::over() 的东西?要获取显示 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

enter image description here

最佳答案

您的示例数据

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))

您可以使用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

或者你可以这样做(通过 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

或者只是这样

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

关于r - `sp::over()` 相当于 `terra`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70746682/

相关文章:

r - 如何使用wav文件的URL在R中加载wav文件?

r - 在 R 中使用 RNN (Keras) 进行时间序列预测

mysql - 最近的位置数据与空间数据 laravel mysql

r - 在磁盘上的 R 中设置栅格元数据(波段名称)

r - 如何绘制不同长度的向量列表?

r - 使用 R 在 for 循环中创建具有不同名称的向量

java - 映射到 com.vividsolutions.jts.geom.Point 无效的字节序标志

spatial - 有没有办法确定 sf 中多边形的主要方向?

r - 使用 terra::predict 和 caret::train ranger 模型生成物种分布的预测栅格