I have 2 vectors:
set.seed(1)
x1 = rnorm(100,0,1)
x2 = rnorm(100,1,1)
I want to plot these as lines and then find the intersection points of the lines, also if there are multiple points of intersection then I want to locate each of them.
I have come across a similar question,and tried to solve this problem using spatstat
, but I was not able to convert my combined data frame containing both vector values to psp object
.
outersect(): The opposite of R's intersect() functionsetdiff() produces all elements of the first input vector without any matching elements from the second input vector (i.e. is asymmetric).
Late response, but here is a "spatial" method using package SP and RGEOS. This requires that both x and y are numeric (or can be converted to numeric). The projection is arbitrary, but epsg:4269 seemed to work well:
library(sp)
library(rgeos)
# dummy x data
x1 = rnorm(100,0,1)
x2 = rnorm(100,1,1)
#dummy y data
y1 <- seq(1, 100, 1)
y2 <- seq(1, 100, 1)
# convert to a sp object (spatial lines)
l1 <- Line(matrix(c(x1, y1), nc = 2, byrow = F))
l2 <- Line(matrix(c(x2, y2), nc = 2, byrow = F))
ll1 <- Lines(list(l1), ID = "1")
ll2 <- Lines(list(l2), ID = "1")
sl1 <- SpatialLines(list(ll1), proj4string = CRS("+init=epsg:4269"))
sl2 <- SpatialLines(list(ll2), proj4string = CRS("+init=epsg:4269"))
# Calculate locations where spatial lines intersect
int.pts <- gIntersection(sl1, sl2, byid = TRUE)
int.coords <- int.pts@coords
# Plot line data and points of intersection
plot(x1, y1, type = "l")
lines(x2, y2, type = "l", col = "red")
points(int.coords[,1], int.coords[,2], pch = 20, col = "blue")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With