2013-04-03 14 views
1

對於無關緊要的問題抱歉,自從我上次來到這裏以後,我的R似乎已經非常生鏽。我有幾個系列接管時間,像這樣的比例的數據:擬合平滑線,限制從0到1

years <- c(1890, 1891, 1894, 1896, 1899, 1905, 1917) 
ratio <- c(0.8, 0.9, 0.5, 0.25, 0.1, 0.02, 0) 
plot(ratio~years) 

疊加在散點圖我需要一個smoothish線即尊重比數據的0到1的範圍。直線lines(predict(loess(ratio~years))~years)有點太生澀了,我嘗試了一些平滑的方法,有時候會用我的真實數據降低到零以下。我需要什麼功能?

回答

3

看起來你似乎你的模型是指數衰減。你可以用非線性最小二乘迴歸估計這一點,使用nls()

fit <- nls(ratio ~ exp(-b*(years-1890)), start=list(b=0.5)) 
fit 

Nonlinear regression model 
    model: ratio ~ exp(-b * (years - 1890)) 
    data: parent.frame() 
    b 
0.2051 
residual sum-of-squares: 0.05669 

Number of iterations to convergence: 5 
Achieved convergence tolerance: 5.016e-06 

現在繪製的結果:

plot(ratio~years, ylim=c(0,1)) 
newdata <- data.frame(years=1890:1917) 
lines(newdata$years, predict(fit, newdata=newdata), col="red") 

enter image description here

+1

好答案 - 只是經過而已提的是,在多一般情況下(即不是很好的指數擬合),使用'smooth.spline'參數可以得到非常好看的擬合曲線。 –