1

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

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

cents <- gCentroid(v, byid = TRUE)

I don't see any associated "ID_1" slot. 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.

2 Answers 2

1

If you read the functions help is specifically states:

Returns a SpatialPoints object of the centroid(s) for spgeom

So, it is not returning a SpatialPointsDataFrame thus, no @data slot. The results remain ordered to the parent polygons so, if you want an ID field, rownames or attributes just pull them from the @data slot from the polygons. The function does not search for an ID field in the @data data.frame. If it is associating anything it would be the rownames.

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

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

cents <- gCentroid(v, byid = TRUE)
  class(cents)
    row.names(cents)

Now, create a SpatialPointsDataFrame from the rownames, centroids and source @data slot

cents <- SpatialPointsDataFrame(cents, 
           data.frame(ID=row.names(cents), v@data))
  class(cents)
    head(cents@data)
1
  • Hey this worked great! Thank you so much
    – seak23
    Jun 8, 2021 at 14:25
0

It would be easier with either terra or sf. For example

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.