2

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

1 Answer 1

5

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.

2
  • This does not work. I get the following error message: Error: trying to get slot "geometry" from an object (class "sf") that is not an S4 object
    – kalakaru
    Apr 10, 2019 at 16:09
  • 1
    I have just updated the answer using the example you provide in the question -- sorry for not noting that before. Apr 12, 2019 at 9:58

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .