R_U*_*ser 16 statistics interpolation 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")
Run Code Online (Sandbox Code Playgroud)
现在我想问一个问题是"如果原始数据集的所有中间数据点都在周围测量值之间的直线上,那么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)
Run Code Online (Sandbox Code Playgroud)
如果你看图:我想得到Y值,其中ablines与已知数据的线性插值相交
abline(v = aim, col = "#ff0000")
Run Code Online (Sandbox Code Playgroud)
因此,在理想情况下,我将使用我已知的数据创建"linearInterpolationModel",例如
model <- linearInterpol(known)
Run Code Online (Sandbox Code Playgroud)
...然后,我可以询问Y值,例如
model$getEstimation(0.3)
Run Code Online (Sandbox Code Playgroud)
(在这种情况下应该给出"3")
abline(h = 3, col = "#00ff00")
Run Code Online (Sandbox Code Playgroud)
我怎么能意识到这一点?手动我会为每个值做这样的事情:
Xsmall
且最接近的X值大于Xlarge
当前X值X
.relPos = (X - Xsmall) / (Xlarge - Xsmall)
Yexp = Ysmall + (relPos * (Ylarge - Ysmall))
至少对于Matlab软件我听说有这种问题的内置函数.
谢谢你的帮助,
斯文
42-*_*42- 18
你可以看approx()
和approxfun()
......或者我想你可以适合用lm
线性或lowess
用于非参数拟合.
Cha*_*ase 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")
Run Code Online (Sandbox Code Playgroud)
当然,您可以直接检索这些预测值:
> cbind(aim, newY)
aim newY
1 0.3 2.4500000
2 0.7 6.1928571
3 2.3 21.1642857
....
Run Code Online (Sandbox Code Playgroud)