R中的线性插值

时间:2011-07-16 23:17:18

标签: r statistics interpolation

我有一个真实数据的数据集,例如:

# Dataset 1 with known data
known <- data.frame(
    x = c(0:6),
    y = c(0, 10, 20, 23, 41, 39, 61)
)

plot (known$x, known$y, type="o")

现在我想得到一个问题的答案 “如果原始数据集的所有中间数据点都在周围测量值之间的直线上,那么0.3的Y值是多少?”

 # X values of points to interpolate from known data
 aim <- c(0.3, 0.7, 2.3, 3.3, 4.3, 5.6, 5.9)

如果你看图:我想得到Y​​值,其中ablines与已知数据的线性插值相交

abline(v = aim, col = "#ff0000")

因此,在理想的情况下,我会用我的已知数据创建一个“linearInterpolationModel”,例如

model <- linearInterpol(known)

...然后我可以询问Y值,例如

model$getEstimation(0.3)

(在这种情况下应该给出“3”)

abline(h = 3, col = "#00ff00")

我怎么能意识到这一点?手动我会为每个值做这样的事情:

  1. 与当前X值Xsmall相比,最接近的X值小Xlarge和最接近的X值大X
  2. 计算较小X值relPos = (X - Xsmall) / (Xlarge - Xsmall)
  3. 的相对位置
  4. 计算预期的Y值Yexp = Ysmall + (relPos * (Ylarge - Ysmall))
  5. 至少对于Matlab软件我听说有这种问题的内置函数。

    感谢您的帮助,

    斯文

2 个答案:

答案 0 :(得分:17)

您可以查看approx()approxfun() ...或者我认为您可以使用lm表示线性或lowess表示非参数拟合。

答案 1 :(得分:11)

要跟进DWin的答案,以下是使用线性模型得到预测值的方法。

model.lm <- lm(y ~ x, data = known)

# Use predict to estimate the values for aim.
# Note that predict expects a data.frame and the col 
# names need to match
newY <- predict(model.lm, newdata = data.frame(x = aim))

#Add the predicted points to the original plot
points(aim, newY, col = "red")

当然,您可以直接检索这些预测值:

> cbind(aim, newY)
  aim       newY
1 0.3  2.4500000
2 0.7  6.1928571
3 2.3 21.1642857
....
相关问题