3

This code creates the desired outline of two combined shapes

square.df <- data.frame("x"=c(0,0,1,1,0),
           "y"=c(0,1,1,0,0),
           "ID"=rep("square",5))
square <- st_cast(st_combine(st_as_sf(square.df,coords = c("x", "y"))),"POLYGON")
plot(square)

triangle.df <- data.frame("x"=c(0,1,0.5,0),
                        "y"=c(1,1,1.5,1),
                        "ID"=rep("triangle",4))
triangle <- st_cast(st_combine(st_as_sf(triangle.df,coords = c("x", "y"))),"POLYGON")
plot(triangle)

plot(st_union(triangle,square))

But what if my data frame has multiple shapes, like this?

shapes.df <- rbind(square.df,triangle.df)
shapes <- st_cast(st_combine(st_as_sf(shapes.df,coords = c("x", "y"))),"POLYGON")
plot(shapes)

What sf object do I create and how do I get the outline of the combined polygons?

1 Answer 1

5

This is an interesting problem; the immediate answer would be to consider sf::st_union() - but your shapes object is not valid; you have to repair it first by calling sf::st_make_valid().

Then (and only then) will the st_union work as expected.

st_is_valid(shapes)
[1] FALSE

house <- shapes %>% 
  st_make_valid() %>% 
  st_union()

plot(house, col = "red")

a house image

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Much more efficient that my loop hack!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.