2014-02-16 37 views
0

這是我迄今爲止所做的。我不知道如何創建的95%置信帶:如何使用預測函數在R中創建置信度帶?

x=rnorm(100,0,1) 
e=rnorm(100,0,4) 
for (i in 1:100){y[i]=2+3*x[i]+e[i]} 
plot(x,y,lty=3) 
estimation_lm=lm(y~x) 
(summary(estimation_lm)) 
(cc=coef(estimation_lm)) 
abline(estimation_lm) 
abline(a=2, b=3,col="red") 

enter image description here

我知道我要使用此代碼,但我不完全相信我應該在新的數據或間隔使用(我想我應該用prediction)這個問題:

predict(object, newdata, interval = "none"/"confidence"/"prediction",level = 0.95) 

更放大的部分版本我被困在: enter image description here

+1

前一段時間我寫了一篇關於如何在R. http://rpubs.com/RomanL/7024 –

+0

@RomanLuštrik這是如此翔實的博客繪製間隔的一點心意。我的問題是,從這個問題我沒有得到什麼新的數據要插入預測公式。謝謝! –

+1

您無法在預測中插入公式,但可以手動計算。你可以從'predict'中得到'\ hat {y}','x'是你的原始值,你可以用'qt'來得到't'。見'TDist'。 –

回答

0

s_yhat公式表明請求的間隔是平均值,而不是單個數據。在這種情況下,要在predict函數中使用的正確參數是interval="confidence"。請看下圖:

library(gplots) # plotCI 

data = data.frame(matrix(0, nrow=100, ncol=2)) 
colnames(data) = c("x", "y") 
data$x = rnorm(100,0,1) 
e = rnorm(100,0,4) 
for (i in 1:100) { 
    data$y[i] = 2 + 3*data$x[i] + e[i] 
} 
plot(data$x, data$y, xlab="x", ylab="y", pch=20) 
estimation_lm = lm(y~x, data) 
(summary(estimation_lm)) 
(coef(estimation_lm)) 
abline(estimation_lm) 
abline(a=2, b=3, col="red", lty="dotted") 
predict = predict(estimation_lm, data, interval="confidence", level=0.95) 
plotCI(data$x, predict[,1], li=predict[,2], ui=predict[,3], add=T, col="blue", gap=0, pch=NA_integer_) 
legend("bottomright", legend=c("estimated regression", "true line", "confidence interval 95%"), lty=c("solid", "dashed", "solid"), col=c("black", "red", "blue")) 

enter image description here

+0

聽起來像你沒有使用學生髮布的新數據?! –

+0

'predict'函數確實使用學生分佈來計算置信區間。看一下'predict.lm'源代碼的第146和147行。 – Baumann

+0

爲什麼你有這行代碼? 'data = data.frame(matrix(0,nrow = 100,ncol = 2))'我的意思是問題的哪一部分描述了你應該有那行代碼? –