You can do this with the spatstat
package, but you need to convert
from SpatialLines
and SpatialPolygons
to psp
(planar segment
pattern) and owin
(observation window -- a polygon in the plane) using
the maptools
package.
Since you didn't provide example data I will first construct
SpatialPolygons and SpatialLines objects looking like your graphic:
library(maptools)
#> Loading required package: sp
#> Checking rgeos availability: TRUE
library(spatstat)
#> Loading required package: nlme
#> Loading required package: rpart
#>
#> spatstat 1.48-0.029 (nickname: 'Alternative Facts')
#> For an introduction to spatstat, type 'beginner'
A <- owin(c(1,3), c(2,5))
B <- owin(c(4,7), c(1,5))
p <- union.owin(A,B)
p <- as(p, "SpatialPolygons")
l <- psp(c(0.5, 0.5), c(2, 4), c(4, 6), c(2, 4), window = owin(c(0,7), c(0,5)))
l <- as(l, "SpatialLines")
plot(p)
plot(l, col = "green", add = TRUE, lwd = 3)
Now to do what you ask you convert the edges of the polygon to a psp
and find where the lines cross these edges (returned as a planar point
pattern ppp
):
l <- as(l, "psp")
p <- as(p, "owin")
e <- edges(p)
x <- crossing.psp(l, e)
x
#> Planar point pattern: 4 points
#> window: rectangle = [1, 6] x [2, 4] units
Adding the points to the plots shows what we found:
plot(p, main = "")
plot(l, col = "green", add = TRUE, lwd = 3)
plot(x, add = TRUE, col = "red", pch = 20, cex = 3)