【问题标题】:How to interpolate a single point where line crosses a baseline between two points [duplicate]如何在线与两点之间的基线交叉的地方插入一个点[重复]
【发布时间】:2019-04-26 22:59:20
【问题描述】:

我是 R 的新手,但我正在尝试找出一种自动方法来确定两点之间的给定线与基线相交的位置(在本例中为 75,请参阅下面图片链接中的虚线)x-协调。一旦找到 x 值,我希望将其添加到 y 值向量中所有 x 值和相应 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)

【问题讨论】:

标签: r


【解决方案1】:

编辑:添加了原始数据+交叉点组合数据框的创建。

改编自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')

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

【讨论】:

  • 乔恩,非常感谢您抽出宝贵时间帮我研究这个问题。在 R 中仍然是新的,有没有办法用原始的 x 和 y 坐标向量集以正确的顺序插入找到的点(图上的蓝色)? (例如,newx 将具有 c(1,2,3,4,4.71,5,5.33,6,7,8,9,10) 而 newy 将具有 c(75,53,37,25,75,95, 75,35,50,75,75,75))
  • 已添加到答案中,希望对您有所帮助。
  • 使用 'for' 循环为 xs 和 ys 行提供输出会有那么难吗?此外,如果某些行在列中不均匀,例如没有识别出新点,是否会出现问题?谢谢!
  • 当 xs 没有完美间隔时,有没有办法做到这一点?例如,如果第一个 x 为零 (c(0,2,3,4,5,6,7,8,9,10)),该函数似乎不会返回正确的结果,它会添加一个“x=1, y=75”的行
  • 我发现返回第一个元素的正确 x 值存在问题。唔。黑客修复可能是添加一个虚拟的第一个值以丢弃,但我会尝试纠正它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-17
  • 2017-09-26
  • 1970-01-01
相关资源
最近更新 更多