R:为同一 x 的上升和下降肢体插值 y

R: Interpolate y for rising and falling limbs for the same x

我得到一个顺时针循环的 x,y 数据。在 R 中,我想确定中点 x 值 (Xmid),然后在两个肢体上为相同的 Xmid.

插入 y 值
x <- c(1.62, 1.82,2.09, 2.48, 2.19, 1.87, 1.67)
y <- c(238, 388, 721, 744, 307, 246, 222)

plot(x, y, type = 'l')

mid <- function(x){
  0.5*(max(x, na.rm = T) - min(x, na.rm = T)) + min(x,na.rm = T)
} 

但是!当我使用 approx 函数时,它 returns 只有一个 y 值(对于上升肢)。如何获得第二个(对于下肢)?也许还有其他功能可以做到这一点?

> approx(x, y, xout = mid(x))
$x
[1] 2.05

$y
[1] 634.6364

换句话说,我正在尝试这样做:来自 [Lawler et al., 2006] 的图形示例是 here

由于数据不规则(它不对应于 "proper" 函数),您将不得不自己找到所有交叉点。我想你可以用

之类的东西来做到这一点
target <- mid(x)
idx <- which(abs(diff(sign(x-target)))>0)

找到位于您感兴趣的 x 值两侧的所有点对,然后您可以提取每个点的 y 值

f <- function(i, target) approx(c(x[i], x[i+1]), c(y[i], y[i+1]), xout=target)$y
yp <- sapply(idx, f, target=target)

然后你可以绘制结果

abline(v=target, lty=2)
points(rep(target, length(yp)), yp, col="red", cex=2)