[R] Confidence intervel for regression line

Rolf Turner rolf.turner at xtra.co.nz
Tue Jan 15 01:09:52 CET 2013


On 01/15/2013 09:17 AM, li li wrote:
> Hi all,
>     For the simple linear regression, I want to find the input "x" value so
> that the
> lower confidnece limit is a specific number, say 0.2.
>     In other words, I want to find the value of x so that the lower
> confidence bound crosses the horizontal line 0.2.
>     Is there a simple way (an R function) that can do this?

I don't know of an extant R function, but it's simple enough.  You just
need to solve a quadratic equation.

Here's my effort at writing an R function to effect this:

xForCb <- function(model,level,cb) {
s2  <- summary(model)$sigma^2
Cov <- summary(model)$cov.unscaled*s2
ccc <- coef(model)
df  <- model$df.residual
q   <- qt(level,df)
A   <- ccc[2]^2 - q^2*Cov[2,2]
B   <- 2*((cb-ccc[1])*(-ccc[2]) - q^2*Cov[1,2])
C   <- (cb - ccc[1])^2 - q^2 * Cov[1,1]
r1  <- (-B + sqrt(B^2 - 4*A*C))/(2*A)
r2  <- (-B - sqrt(B^2 - 4*A*C))/(2*A)
y1  <- ccc[1] + ccc[2]*r1
y2  <- ccc[1] + ccc[2]*r2
res <- c(r1,r2)[order(c(y2,y1))]
names(res) <- c("x.for.lb","x.for.ub")
res
}

E.g. of use:

set.seed(42)
x    <- seq(0,10,length=101)
y    <- 1.5 + 2.5*x + rnorm(101,0,5)
fit   <- lm(y ~ x)
pfit <- predict(fit,interval="confidence",level=0.90)
plot(x,y)
lines(x,pfit[,"fit"])
lines(x,pfit[,"upr"],col="red")
lines(x,pfit[,"lwr"],col="green")
xx <- xForCb(fit,0.95,5)
abline(v=xx,col="blue")
abline(h=5,col="blue")

     cheers,

         Rolf



More information about the R-help mailing list