1

Does anybody know of a way to create a single polygon (that will eventually be converted to an Owin) from either a spatialpoints object or a spatiallines object?

Here is an example of each:

enter image description here

enter image description here

Here's some very cut down code for this:

test.verts <- list()
test.verts$x <- c(518, 594, 421, 286, 104, 129, 315)
test.verts$y <- c(273, 608, 1202, 1201, 620, 285, 135)

test.owin <- spatstat::owin(poly = test.verts)

cltest <- create.lines(test.owin, nlines=20, width = 5,spacing=NULL,angle=0)

x0list <- c(cltest$x0)
meanx0 <- lapply(x0list, mean)
y0list <- c(cltest$y0)
meany0 <- lapply(y0list, mean)

x1list <- c(cltest$x1)
meanx1 <- lapply(x1list, mean)
y1list <- c(cltest$y1)
meany1 <- lapply(y1list, mean)

pspowin <- owin(xrange=c(min(unlist(meanx0)),max(unlist(meanx1))), 
                yrange=c(min(unlist(meany0)),max(unlist(meany0))))

psplines1 <- as.psp(cltest, window = pspowin)

coords <- psplines1$ends
nc <- nrow(coords)
out <- vector(mode="list", length=nc)

for (i in seq(along=out)) {
  lLine <-Line(cbind(c(coords[i,1], coords[i,3]), c(coords[i,2],
                                                    coords[i,4])))
  out[[i]] <- Lines(list(lLine), ID=i)
}

aix.lines <- SpatialLines(out)

plot(aix.lines) #lines needing to be connected

sflines <- st_as_sf(aix.lines)

pt <- st_cast(sflines, "POINT") #points needing to be connected; can also convert to SpatialPoints from sp

plot(pt)
1

For the example you've shown a convex hull is the easiest way to enclose all points in a polygon. For a sp object you could use the convex hull algorithm from rGeos. I'm not sure if rGeos is compatible with sf. If any of your desired polygons has a concave vertex you'll need a routine that traces the points in a specified order.

1
  • That's way more simple than I expected, thank you! Nov 7 '19 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.