Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Finding the intersect of two lines

Tags:

r

I have this simple code that creates 3 matrices and plots them:

Y=matrix(c(1,2,3,4), nrow=1)
X1=matrix(c(2,3,3.5,4.5))
X2=matrix(c(0.1, 0.2, 0.6, 1.1), nrow=1)
#Plotting
plot(X1, Y)+lines(X1,Y)
par(new=TRUE)
plot(X2, Y)+lines(X2,Y) + abline(v=0.4, col="red")

And here is the plot: enter image description here

Now, I want for the X value 0.4 to get all the Y values. The Y values are the values where the red line crosses the other two lines. So there should be two values, one value Y1 for one line and the other Y2 value for the other line.

Is there maybe any function that I could use to do this? I would really appreciate any suggestion how to do this.

like image 385
Ville Avatar asked Mar 27 '18 19:03

Ville


People also ask

How to find the intersection between two or more lists in R?

The intersection of lists means the elements that are unique and common between the lists. For example, if we have a list that contains 1, 2, 3, 3, 3, 2, 1 and the other list that contains 2, 2, 1, 2, 1 then the intersection will return only those elements that are common between ...

How do you find the intersection of two lines?

To find the intersection between two lines y = ax + b and y = cx + d the first step that must be done is to set ax + b equal to cx + d. Then solve this equation for x. This will be the x coordinate of the intersection point.

Is there a function called intersect in R?

Note: There are several different packages available that provide a function called intersect (e.g. Base R, dplyr, lubridate, and generics). Depending on what you want to do, those functions may have to be applied differently.

How do you find the y coordinate of the intersection point?

Then you can find the y coordinate of the intersection by filling in the x coordinate in the expression of either of the two lines. Since it is an intersection point both will give the same y coordinate.


2 Answers

Because the two graphs use different x scales, this is a rather odd question. Getting the crossing point for the X2 line is easy, but the X1 line is a little more complicated.

## X2 line
AF2 = approxfun(X2, Y)
AF2(0.4)
[1] 2.5

The problem with the X1 line is that 0.4 on your graph means only X2=0.4, but X1 != 0.4. You can see that the 0.4 mark is half way between X1 = 2.5 and X1= 3, so we need to compute that value using X1 = 2.75.

AF1 = approxfun(X1, Y)
AF1(2.75)
[1] 1.75

Confirm with graph:

#Plotting
plot(X1, Y)+lines(X1,Y) + abline(v=0.4, col="red")
par(new=TRUE)
plot(X2, Y)+lines(X2,Y) 
abline(v=0.4)
points(c(0.4,0.4), c(1.75, 2.5), pch=20, col="red")

Crazy Graph

like image 64
G5W Avatar answered Oct 13 '22 00:10

G5W


identify() can be used to locate points in a scatter plot by clicking with the mouse in the plot area. Hope this is what you're looking for. Check it out!

like image 37
bala83 Avatar answered Oct 13 '22 00:10

bala83