How can I create a confidence interval in r from a linear model?

362 Views Asked by At

I want to create a linear model of y vs x and use it to find a confidence interval for y given a observed value of x.

So I created some samples:

x=rnorm(100,2)
y=rnorm(100,2)

and created the linear model:

bbbb=lm(y~x)

But when I use predict to create the confidence intervals, it gives me a bunch list of confidence intervals rather than a single one?

predict(bbbb,x=2,interval="confidence")

returns:

...
51  2.188294 1.949615 2.426973
52  2.189329 1.932474 2.446183
53  2.176816 1.950111 2.403521
54  2.183961 1.998136 2.369786
...

How can I make it return just one confidence interval for y when x=2?

1

There are 1 best solutions below

0
On

You need:

predict(bbbb, newdata = data.frame(x = 2), interval  = "confidence")

for reasons that are clear when you look at ?predict.lm.

The newdata argument is required to be a data frame. You supplied a length 1 vector. Secondly, because of the way S3 methods work, what you thought you were passing to newdata was actually not passed to newdata at all. You actually specified a new argument x with value 2, which predict() promptly forgot about (it got mopped up by the ... argument). If newdata is not supplied, predict() uses the data stored in the fitted model object (bbbb) and returns the fitted values plus any requested extras like CI, standard errors etc.