簡體   English   中英

使用 gCentroid 在 R 中查找多個多邊形的質心時保留 ID

[英]Preserving IDs when using gCentroid to find centroids of multiple polygons in R

這似乎應該很簡單。 我在一個 shapefile 中包含多個多邊形,我正在使用 rgeos 的gCentroid() function 創建一堆質心點。 function 有一個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"]] 

所以當我在 go 上創建質心時

cents <- gCentroid(v, byid = TRUE)

我沒有看到任何關聯的“ID_1”插槽。 問題是我最終將使用這些質心從柵格中獲取值,並且需要 ID 來區分值來自哪個多邊形。

簡單的方法是

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)

暫無
暫無

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

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