2

Simple question: how to extract the number of vertices in each polygon in R?

I've found one way that works, but this is very slow (when x is a SpatialPolygonsDataFrame):

y <- fortify(x) 
n.verts <- aggregate(y, by=list(y$id), FUN=length)[,2]
x@data$nverts <- n.verts 
4

If the SpatialPolygonsDataFramehas just one part for each polygon, you can use the following:

# test data from www.gadm.org: administrative boundaries Liechtenstein/Level 1
R> load("LIE_adm1.RData")

# check number of parts
R> sapply(gadm@polygons, function(x) length(x))
 [1] 1 1 1 1 1 1 1 1 1 1 1

# number of vertices
R> sapply(gadm@polygons, function(y) nrow(y@Polygons[[1]]@coords))
 [1]  307  169  383  675   64  572  431  617 1389  425  456
  • ps system.time(sapply(dshe@polygons, function(y) nrow(y@Polygons[[1]]@coords))) tells me your method is several orders of magnitude faster than mine. – RobinLovelace Apr 16 '13 at 14:25
  • doesn't work if there is a polygon feature which contains more parts! (Like more "islands" in one polygon feature). In that case, number of vertices for one of the islands is reported instead of the sum of all! – Tomas Aug 13 '18 at 8:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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