【问题标题】:Preserving IDs when using gCentroid to find centroids of multiple polygons in R使用 gCentroid 在 R 中查找多个多边形的质心时保留 ID
【发布时间】:2021-06-07 22:07:46
【问题描述】:

这看起来应该很简单。我在一个 shapefile 中包含多个多边形,我正在使用 rgeos 的 gCentroid() 函数来创建一堆质心点。该函数有一个 id 参数,如果未指定,它应该返回父几何 ID,但这要么不起作用,要么我看错了地方,或者我误解了参数。

简单示例:

library(terra)
library(rgeos)
library(sp)

v <- vect(system.file("ex/lux.shp", package="terra"))
v <- as(v, "Spatial")

#Clearly there are IDs here (albeit not unique) 
v@data[["ID_1"]] 

所以当我继续创建质心时

cents <- gCentroid(v, byid = TRUE)

我没有看到任何关联的“ID_1”广告位。问题是我最终将使用这些质心从栅格中获取值,并且需要 ID 来区分值来自哪个多边形。

【问题讨论】:

  • 您可能想查看sf 包中的st_centroid。使用此函数将保留父几何体中的原始属性。

标签: r polygon raster sp centroid


【解决方案1】:

简单的方法是

library(terra)
v <- vect(system.file("ex/lux.shp", package="terra"))
x <- centroids(v)

sf

library(sf)
y <- st_centroid(st_as_sf(v))

使用 rgeos,您需要按照这些思路做一些事情

library(rgeos)
s <- as(v, "Spatial")
cents <- gCentroid(s, byid = TRUE)
atts <- data.frame(v)[as.integer(row.names(cents)), ]
s < SpatialPointsDataFrame(cents, atts)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2019-03-02
    • 2014-06-30
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多