hypertidy / toposhop

2 stars 0 forks source link

st_cast updates for GC #12

Open mdsumner opened 6 years ago

mdsumner commented 6 years ago

There's a few unsupported and inconsistent cases for st_cast (this function "explodes" as well, which makes it less clear what the role is).

re-polygonizing and casting from GC sets of POLYGON should work:

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 %>% 
    st_cast("MULTILINESTRING") %>% 
    st_polygonize() %>% 
    st_cast("MULTIPOLYGON")

bad_poly <- matrix(c(0.5, 0.5,
                     0.4, 5.2,
                     9.8, 1.1,
                     7.6, 8.5,
                     9.5, 8.0,
                     9.4, 6.1,
                     7.4, 0.7,
                     0.5, 0.5), ncol = 2, byrow = TRUE) %>%
    st_polygon(x = list(.)) %>%
    st_sfc() %>%
    st_sf()

## I think this is a bug in st_cast,
## because it otherwise works above, just complains and drops all but the first
bad_poly %>% 
    st_cast("MULTILINESTRING") %>% 
    st_node() %>% 
    st_polygonize() %>% 
    #st_is_valid()
    st_cast("MULTIPOLYGON")

## add nodes and re-polygonize
x <- st_cast(bad_poly, "MULTILINESTRING") %>% 
    st_node() %>% 
    st_polygonize()
st_set_geometry(x, st_sfc(purrr::map(x$geometry, st_multipolygon)))