[英]Linear interpolation in 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")
所以,在理想情况下,我会用我已知的数据创建一个“linearInterpolationModel”,例如
model <- linearInterpol(known)
...然后我可以询问 Y 值,例如
model$getEstimation(0.3)
(在这种情况下应该给出“3”)
abline(h = 3, col = "#00ff00")
我怎么能意识到这一点? 手动我会为每个值做这样的事情:
X
相比,最接近的 X 值更小Xsmall
和最接近的 X 值更大Xlarge
是多少。relPos = (X - Xsmall) / (Xlarge - Xsmall)
Yexp = Ysmall + (relPos * (Ylarge - Ysmall))
至少对于软件 Matlab 听说有内置的 function 针对此类问题。
谢谢你的帮助,
斯文
您可能正在查看approx()
和approxfun()
...或者我想您可以使用lm
进行线性拟合,或者lowess
进行非参数拟合。
为了跟进 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")
当然,您可以直接检索这些预测值:
> 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.