[GIS] Extract number of vertices in each polygon in R

rvertices

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 

Best Answer

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