David Ranzolin
David Ranzolin

Reputation: 1074

How do I partition a circle into equal MULTIPOLYGON "slices" with sf and R?

I have this circle:

library(sf)
p <- st_sfc(st_point(c(0, 1))) 
circle <- st_buffer(p, dist = 1)  
plot(circle)

sf_circle

How do I partition this circle into 4 equal "slices"? 6 equal slices? 8 equal slices? Etc. The object I need returned would be a MULTIPOLYGON.

Upvotes: 1

Views: 463

Answers (1)

Spacedman
Spacedman

Reputation: 94182

Take these two functions, one to create a single wedge given a centre, radius, start angle, width, and number of sections in the arc part, and another to create a number of those with different start angles:

st_wedge <- function(x,y,r,start,width,n=20){
    theta = seq(start, start+width, length=n)
    xarc = x + r*sin(theta)
    yarc = y + r*cos(theta)
    xc = c(x, xarc, x)
    yc = c(y, yarc, y)
    st_polygon(list(cbind(xc,yc)))   
}

st_wedges <- function(x, y, r, nsegs){
    width = (2*pi)/nsegs
    starts = (1:nsegs)*width
    polys = lapply(starts, function(s){st_wedge(x,y,r,s,width)})
    mpoly = st_cast(do.call(st_sfc, polys), "MULTIPOLYGON")
    mpoly
}

Then do something like this to get five wedges centred at 5,1 of radius 10:

> w5 = st_wedges(5,1,10,5)
> plot(w5)
> class(w5)
[1] "sfc_MULTIPOLYGON" "sfc"             
> axis(1)
> axis(2)

enter image description here

Upvotes: 7

Related Questions