1

I have a polygon and two lines. How can I remove the portion of each line that falls within the polygon?

# polygon
coords <- matrix(c(-1.798123, -1.793072, -1.805767, -1.804129, -1.798123, 55.68066, 55.67369, 55.67508, 55.68139, 55.68066), ncol=2)
myPolygon <- Polygons(list(Polygon(coords)),  "myPolygon")
myPolygon <- SpatialPolygons(list(myPolygon))
proj4string(myPolygon) <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
plot(myPolygon)


# lines
line1 <- matrix(c(-1.79880, -1.79517, 55.67737, 55.67920), ncol=2)
line2 <- matrix(c(-1.80231, -1.80679, 55.67764, 55.68004), ncol=2)
line1L <- Line(line1)
line2L <- Line(line2)
my.lines <- Lines(list(line1L, line2L), ID="my.lines")
myLines <- SpatialLines(list(my.lines))
proj4string(myLines) <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
plot(myLines, add=T)

enter image description here

  • So you just need a vector layer clip-function in R then. Have a look for instance at the rgeos package – Curlew Jun 6 '13 at 21:06
1

The gDifference function from the rgeos package is probably your best/easiest bet.

Returns the regions of geometry1 that are not within geometry2.

For reference, the example from the above link (substitute your polygon/line geometries):

x = readWKT("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))")
y = readWKT("POLYGON ((3 3, 7 3, 7 7, 3 7, 3 3))")

d = gDifference(x,y)
plot(d,col='red',pbg='white')

d2 = gDifference(y,x)

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.