Skip to content
Prev 138941 / 398506 Next

polygon shapefile from line edge coordinate list

Murray Richardson <murray.richardson <at> utoronto.ca> writes:
How many polygons in each data.frame? If more than one, how are they 
separated? You note below that there are multiples, are they flagged by 
for example an NA row, or is there a jump from (endX endY) to the next 
(startX startY)?
Are the line segments ordered in sequence. If they are, something like:

xy0 <- data.frame(sX=c(1,2,2,1,3,4,4,3), sY=c(1,1,2,2,3,3,4,4), 
  eX=c(2,2,1,1,4,4,3,3), eY=c(1,2,2,1,3,4,4,3))

brks <- logical(nrow(xy0))
for (i in 2:nrow(xy0)) brks[i] <- (xy0$sX[i] != xy0$eX[i-1]) & 
  (xy0$sY[i] != xy0$eY[i-1])
cbrks <- cumsum(brks)+1
# find the separate polygons

xy1 <- split(xy0, cbrks)

library(sp)
Plist <- vector(mode="list", length=length(xy1))
for (i in seq(along=Plist)) {
  crds <- rbind(cbind(xy1[[i]]$sX, xy1[[i]]$sY), 
    c(xy1[[i]]$eX[nrow(xy1[[i]])], xy1[[i]]$eY[nrow(xy1[[i]])]))
#   close the polygon
  Plist[[i]] <- Polygons(list(Polygon(crds)), ID=names(xy1[i]))
}
# make a list of Polygons objects with IDs

Plist1 <- SpatialPolygons(Plist)
plot(Plist1, axes=TRUE)
SPDF <- SpatialPolygonsDataFrame(Plist1, data=data.frame(i=names(xy1), 
  row.names=names(xy1)))
# convert this to a SpatialPolygonsDataFrame object for export

library(maptools)
writePolyShape(SPDF, "chulls")

If the segments are not in "join up the dots" sequence, it will be 
(even) more messy. Please also consider whether the R-sig-geo list 
might not be more relevant.

Roger