R 中的线性插值
我有一个真实数据的数据集,例如如下所示:
# 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")
所以,在理想情况下,我会用我的已知数据创建一个“线性插值模型”,例如
model <- linearInterpol(known)
......然后我可以询问 Y 值,例如
model$getEstimation(0.3)
(在本例中应该给出“3”)
abline(h = 3, col = "#00ff00")
我怎样才能实现这一点?我会手动对每个值执行如下操作:
- 比当前 X 值
更小的最近的 X 值
Xsmall
和更大的最近的 X 值Xlarge
是多少>X。 - 计算与较小 X 值的相对位置
relPos = (X - Xsmall) / (Xlarge - Xsmall)
- 计算预期 Y 值
Yexp = Ysmall + (relPos * (Ylarge - Ysmall) ))
至少对于Matlab这个软件我听说有一个针对此类问题的内置函数。
谢谢你的帮助,
斯文
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?"
# 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
abline(v = aim, col = "#ff0000")
So, in the ideal case I would create a "linearInterpolationModel" with my known data, e.g.
model <- linearInterpol(known)
... which I can then ask for the Y values, e.g.
model$getEstimation(0.3)
(which should in this case give "3")
abline(h = 3, col = "#00ff00")
How can I realize this? Manually I would for each value do something like this:
- What is the closest X-value smaller
Xsmall
and the closest X-value largerXlarge
than the current X-valueX
. - Calculate the relative position to the smaller X-Value
relPos = (X - Xsmall) / (Xlarge - Xsmall)
- Calculate the expected Y-value
Yexp = Ysmall + (relPos * (Ylarge - Ysmall))
At least for the software Matlab I heard that there is a built-in function for such problems.
Thanks for your help,
Sven
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了跟进 DWin 的答案,以下是如何使用线性模型获得预测值的方法。
当然,您可以直接检索这些预测值:
To follow up on DWin's answer, here's how you'd get the predicted values using a linear model.
And of course you can retrieve those predicted values directly:
您可以查看
approx()
和approxfun()
...或者我想您可以使用lm
来表示线性或lowess
用于非参数拟合。You could be looking at
approx()
andapproxfun()
... or I suppose you could fit withlm
for linear orlowess
for non-parametric fits.