关于回归的 95% CI 的方程式?

Equation for 95% CI on regression?

我有 calculated/plotted 线性和 95% CI 模型参数如下

lm <- lm(cars$speed~cars$dist)

conf <- predict(lm, interval='confidence')
conf <- cbind(cars,conf)

CI <- as.data.frame(confint(lm))

library(ggplot2)

plot<-ggplot(conf,aes(dist,speed)) +
  geom_line(aes(y=fit),color='black') +
  geom_line(aes(y=lwr),color='red',linetype='dashed') +
  geom_line(aes(y=upr),color='red',linetype='dashed')
plot

我想知道在图上计算下限和上限(红线)的方程式是什么?我假设这些可以使用 confint() 函数的值来计算? 我尝试像这样计算 lwr 和 upr 值,但我没有得到相同的结果。

lower <- CI[1,1] + CI[2,1]*cars$dist
upper <- CI[1,2] + CI[2,2]*cars$dist

下面是 lm.predict 中的置信区间是如何使用以下等式计算的:

可以这样实现:

my.lm <- lm(cars$speed~cars$dist)

intercept <- model.matrix(delete.response(terms(my.lm)), cars)
fit.values <- c(intercept %*% coef(my.lm))

data.fit <- data.frame(x=cars$dist, fit=fit.values)

# compute t-value
tval <- qt((1-0.95)/2, df=nrow(data.fit)-2)

# compute Sxx
Sxx <- sum((data.fit$x - mean(data.fit$x))^2)

# compute MSres
MSres <- sum(my.lm$residuals^2)/(nrow(data.fit)-2)

# calculate confidence interval
CI <- data.frame(t(apply(data.fit, 1, FUN =  function(row){
  sqrt(MSres * (1/nrow(data.fit) + (as.numeric(row[1]) - mean(data.fit$x))^2/Sxx)) * tval * c(1, -1) + as.numeric(row[2])
})))
names(CI) <- c("lwr","upr")

head(CI)
#        lwr      upr
#1  6.917090 10.31299
#2  8.472965 11.40620
#3  7.307526 10.58483
#4 10.764584 13.08820
#5  9.626909 12.23906
#6  8.472965 11.40620

您可以将结果与您从 predict 获得的结果进行比较。

希望对您有所帮助。