简体   繁体   English

R 中的线性插值

[英]Linear interpolation in R

I have a dataset of real data, for example looking like this:我有一个真实数据的数据集,例如看起来像这样:

# 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")

Now I want to get an aswer to the question "What would the Y value for 0.3 be, if all intermediate datapoints of the original dataset, are on a straight line between the surrounding measured values?"现在我想回答这个问题“如果原始数据集的所有中间数据点都在周围测量值之间的直线上,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)

If you look at the graph: I want to get the Y-Values, where the ablines intersect with the linear interpolation of the known data如果您查看图表:我想获得 Y 值,其中 ablines 与已知数据的线性插值相交

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

So, in the ideal case I would create a "linearInterpolationModel" with my known data, eg所以,在理想情况下,我会用我已知的数据创建一个“linearInterpolationModel”,例如

model <- linearInterpol(known)

... which I can then ask for the Y values, eg ...然后我可以询问 Y 值,例如

model$getEstimation(0.3)

(which should in this case give "3") (在这种情况下应该给出“3”)

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

How can I realize this?我怎么能意识到这一点? Manually I would for each value do something like this:手动我会为每个值做这样的事情:

  1. What is the closest X-value smaller Xsmall and the closest X-value larger Xlarge than the current X-value X .与当前 X 值X相比,最接近的 X 值更小Xsmall和最接近的 X 值更大Xlarge是多少。
  2. Calculate the relative position to the smaller X-Value relPos = (X - Xsmall) / (Xlarge - Xsmall)计算相对 position 到较小的 X-Value relPos = (X - Xsmall) / (Xlarge - Xsmall)
  3. Calculate the expected Y-value Yexp = Ysmall + (relPos * (Ylarge - Ysmall))计算预期的 Y 值Yexp = Ysmall + (relPos * (Ylarge - Ysmall))

At least for the software Matlab I heard that there is a built-in function for such problems.至少对于软件 Matlab 听说有内置的 function 针对此类问题。

Thanks for your help,谢谢你的帮助,

Sven斯文

You could be looking at approx() and approxfun() ... or I suppose you could fit with lm for linear or lowess for non-parametric fits.您可能正在查看approx()approxfun() ...或者我想您可以使用lm进行线性拟合,或者lowess进行非参数拟合。

To follow up on DWin's answer, here's how you'd get the predicted values using a linear model.为了跟进 DWin 的回答,以下是使用线性 model 获得预测值的方法。

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")

And of course you can retrieve those predicted values directly:当然,您可以直接检索这些预测值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM