On 22-Nov-11 21:25:56, Monica Pisica wrote: > Hi everyone, > > I am trying to get a point of intersection between a > polyline and a straight line .. and get the x and y > coordinates of this point. > For exemplification consider this: > > set.seed(123) > k1 <-rnorm(100, mean=1.77, sd=3.33) > k1 <- sort(k1) > q1 <- rnorm(100, mean=2.37, sd=0.74) > q1 <- sort(q1, decreasing = TRUE) > plot(k1, q1, xlim <- c((min(k1)-5), (max(k1)+5)), type="l") > > ya <- 2 > xa = -5 > yb=4 > xb=12 > lines(c(xa, xb), c(ya, yb), col = 2) > ># I want to get the x and y coordinates of the ># intersection of the 2 lines. > > m <- (ya-yb)/(xa-xb) > b <- ya-m*xa > ln <- loess(q1~k1) > lines(ln) > > It is clear that the x, y will satisfy both linear equations, > y = m*x + b and the ln polyline - .. but while I can visualize > the equation of the straight line - I have problems with the > polyline. I will appreciate any ideas to solve this problem. > I thought it a trivial solution but it seems I cannot see it. > Thanks, > Monica
ya <- 2 xa = -5 yb = 4 xb = 12 These define a line y = ya + (x - xa)*(yb - ya)/(xb - xa) so write this as y = A + B*x Then points above the line satisfy y > A + B*X and points below the line satisfy Y < A + B*X A <- ya - xa*(yb - ya)/(xb - xa) B <- (yb - ya)/(xb - xa) So now extract the points (x,y) fron the loess fit: x.ln <- ln$x y.ln <- ln$y and now find the points on 'ln' which are above, and the points on ln which are below, which will locate the segment which crosses the (X,Y) line: ix.upper <- which(y.ln > A + B*ln$y) ix.lower <- which(y.ln <=3D A + B*ln$y) ix.upper # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15=20 So now you have the line segment from (x.ln[15],y.ln[15]) to (x.ln[16],y.ln[16]) and now all you need to do is to find the intersection of the line from (ln.x[15],ln.y[15]) to (ln.x[16],ln.y[16]) with the line from (xa,ya) to (xb,yb). (There could be complications if the y-values of ln do not continually decrease in value; but happily they do decrease in your example). Hoping this helps! Ted. -------------------------------------------------------------------- E-Mail: (Ted Harding) <ted.hard...@wlandres.net> Fax-to-email: +44 (0)870 094 0861 Date: 22-Nov-11 Time: 22:49:54 ------------------------------ XFMail ------------------------------ ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.