如何在直线与两点之间的基线交叉处插入单个点

时间:2019-04-26 22:59:20

标签: r

我是R的新手,但我试图找出一种自动方法来确定x点上两点之间的给定线与基线的交叉点(在这种情况下,为75,请参见下面的图像链接中的虚线)。坐标。找到x值后,我希望将其添加到所有x值的向量以及y值向量中的相应y值(始终为基线值)。基本上,在输入坐标的所有点之间都有一个函数看一下,看两点之间是否有跨越基线的直线,如果有,将基线处的那些新坐标添加到x,y的输出中向量。我们将不胜感激任何帮助,尤其是在所有x,y坐标之间使它自动化的方面。

https://i.stack.imgur.com/UPehz.jpg

baseline = 75
X <- c(1,2,3,4,5,6,7,8,9,10)
y <- c(75,53,37,25,95,35,50,75,75,75)

1 个答案:

答案 0 :(得分:0)

编辑:添加了创建具有原始数据和交叉点的组合数据框的功能。

改编自another answer related to two intersecting series,且X间距均匀。

baseline = 75
X <- c(1,2,3,4,5,6,7,8,9,10)
Y1 <- rep(baseline, 10)
Y2 <- c(75,53,37,25,95,35,50,75,75,75)

# Find points where x1 is above x2.
above <- Y1>Y2
# Points always intersect when above=TRUE, then FALSE or reverse
intersect.points<-which(diff(above)!=0)
# Find the slopes for each line segment.
Y2.slopes <- (Y2[intersect.points+1]-Y2[intersect.points]) /
  (X[intersect.points+1]-X[intersect.points])
Y1.slopes <- rep(0,length(Y2.slopes))
# Find the intersection for each segment
X.points <- intersect.points + ((Y2[intersect.points] - Y1[intersect.points]) / (Y1.slopes-Y2.slopes))
Y.points <- Y1[intersect.points] + (Y1.slopes*(X.points-intersect.points))
# Plot.
plot(Y1,type='l')
lines(Y2,type='l',col='red')
points(X.points,Y.points,col='blue')

enter image description here

library(dplyr)
combined <- bind_rows(   # combine rows from...
  tibble(X, Y2),         # table of original, plus
  tibble(X  = X.points, 
         Y2 = Y.points)) %>%  # table of interpolations
  distinct() %>%         # and drop any repeated rows
  arrange(X)             # and sort by X

> combined
# A tibble: 12 x 2
       X    Y2
   <dbl> <dbl>
 1  1       75
 2  2       53
 3  3       37
 4  4       25
 5  4.71    75
 6  5       95
 7  5.33    75
 8  6       35
 9  7       50
10  8       75
11  9       75
12 10       75