如何确定一个点是否高于或低于连接R点的线?

时间:2015-12-18 20:30:01

标签: r regression curve-fitting

目的:

  

给定一组数据,我如何确定新数据点是否高于或低于连接点的线。

例如,我如何确定所显示的红点是否在线的上方或下方(没有目视检查)?

![enter image description here

我想在这些点上插入一条确切的线。基本上连接点,并需要一个适合能够使用线上的任何点作为比较器。

目前的尝试:

  

到目前为止,我已经尝试将各种样条拟合到数据中,但它仍然有点过于平滑。我真的在寻找一个完全适合数据,尖角和所有。

我尝试了一个自然样条曲线(以及smooth.splines),但是不能完全准确/足够锐利:

plot(df$lowerx, df$lowery, type='b', xlab='x', ylab='y', pch=21, bg='steel blue')
myspline <- splinefun(df$lowerx, df$lowery, method='natural')
curve(myspline, add=T, from = 0, to=140, n = 100, col='green')

enter image description here

我认为一旦我得到合适的权利,就可以直接用它来判断点数是高于还是低于线(例如使用预测或函数),但我需要帮助。

也完全欢迎另一种方法。

数据:

df <- structure(list(lowerx = c(11.791, 18.073, 23.833, 35.875, 39.638, 44.153, 59.206, 71.498, 83.289, 95.091, 119.676, 131.467, 143.76), lowery = c(5.205, 5.89, 6.233, 9.041, 10, 10.342, 12.603, 13.493, 14.658, 15.274, 15.89, 15.616, 15.342)), .Names = c("lowerx", "lowery"), class = "data.frame", row.names = c(NA, -13L))

2 个答案:

答案 0 :(得分:9)

R函数approxfun将创建一个执行线性插值的函数。

> F <- approxfun(x=df$lowerx, y=df$lowery)
> F(80) > 13
[1] TRUE

我使用了您提供的数据并在&#34;红点&#34;的坐标处测试了我的最佳猜测。 as(80,13),所以它说13小于插值而且(80,15)在上面:

> F(80) > 15
[1] FALSE

答案 1 :(得分:0)

这篇文章展示了如何做到这一点:How to tell whether a point is to the right or left side of a line

如果位置为+1,则该点位于上方,如果该位为-1,则该点位于下方,如果为0则直接位于该线上,不需要拟合,您只需要知道哪两个点指向跨越该线。 ..

应用于您的示例:

df <- structure(list(lowerx = c(11.791, 18.073, 23.833, 35.875, 39.638, 44.153, 59.206, 71.498, 83.289, 95.091, 119.676, 131.467, 143.76), lowery = c(5.205, 5.89, 6.233, 9.041, 10, 10.342, 12.603, 13.493, 14.658, 15.274, 15.89, 15.616, 15.342)), .Names = c("lowerx", "lowery"), class = "data.frame", row.names = c(NA, -15L))

X <- 79
Y <- 13
xIndex2 <- which(df$lowerx > X)[1]
xIndex1 <- xIndex2 - 1
Ax <- df$lowerx[xIndex1]
Ay <- df$lowery[xIndex1]
Bx <- df$lowerx[xIndex2]
By <- df$lowery[xIndex2]
position = sign((Bx - Ax) * (Y - Ay) - (By - Ay) * (X - Ax))