[英]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.