R SF – Count Number of Polygons in Multipolygon Using R SF

polygonrsf

How can I count the number of polygons that are present in a multipolygon with the R package sf? Example: In the following image that represents a multipolygon I count 3 polygons. I want to be able to store this information as an attribute. Below I added the code that creates the multipolygon.

# Create Multipolygon: https://cran.r-project.org/web/packages/sf/vignettes/sf1.html
library(sf)
p1 <- rbind(c(0,0), c(1,0), c(3,2), c(2,4), c(1,4), c(0,0))
p2 <- rbind(c(1,1), c(1,2), c(2,2), c(1,1))
pol <-st_polygon(list(p1,p2))
p3 <- rbind(c(3,0), c(4,0), c(4,1), c(3,1), c(3,0))
p4 <- rbind(c(3.3,0.3), c(3.8,0.3), c(3.8,0.8), c(3.3,0.8), c(3.3,0.3))[5:1,]
p5 <- rbind(c(3,3), c(4,2), c(4,3), c(3,3))
mpol <- st_multipolygon(list(list(p1,p2), list(p3,p4), list(p5)))

mpol_geom = st_sfc(mpol, crs = 4326)   

mpol_attrib = data.frame(                                   
name = "MULTIPOLYGON"
)

mpol_sf = st_sf(mpol_attrib, geometry = mpol_geom)   

plot(mpol_sf)

enter image description here

Best Answer

EDIT -- correcting the answer using your sf object, I note that

length(st_geometry(mpol_sf)[[1]]) or length(mpol_sf$geometry[[1]])

should work.