[英]Preserving IDs when using gCentroid to find centroids of multiple polygons in R
This seems like it should be simple.这似乎应该很简单。 I have multiple polygons contained in one shapefile, and I am using the
gCentroid()
function from rgeos to create a bunch of centroid points.我在一个 shapefile 中包含多个多边形,我正在使用 rgeos 的
gCentroid()
function 创建一堆质心点。 The function has an id
argument which should return the parent geometry Ids if left unspecified, but this is either not working or I'm looking in the wrong spot or I misunderstood the argument. function 有一个
id
参数,如果未指定,它应该返回父几何 ID,但这要么不起作用,要么我找错了地方,或者我误解了这个参数。
Simple example:简单的例子:
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"]]
so when I go on to create centroids所以当我在 go 上创建质心时
cents <- gCentroid(v, byid = TRUE)
I don't see any associated "ID_1" slot.我没有看到任何关联的“ID_1”插槽。 The issue is I will eventually be using these centroids to derive values from a raster, and will need the IDs to distinguish which polygon the values originate from.
问题是我最终将使用这些质心从栅格中获取值,并且需要 ID 来区分值来自哪个多边形。
The easy way would be简单的方法是
library(terra)
v <- vect(system.file("ex/lux.shp", package="terra"))
x <- centroids(v)
of with sf
与
sf
library(sf)
y <- st_centroid(st_as_sf(v))
With rgeos you would need to do something along these lines使用 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.