0
votes

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
Questions like this that focus on a specific software implementation are considered Off Topic on Cross Validated. Your question should probably be closed or moved. - Gavin Simpson
Take out the focus on r, and ask in general how to predict a confidence interval for a given $x$-value. - Carl
@Carl I suspect that's not really the problem here... (suspect this is more about the surprising behaviour of predict()...) - Gavin Simpson
@GavinSimpson Yup, it really is off topic. But, you answered it anyway, so +1 for your answer. Now what? - Carl
@Carl Thanks; my answer was too big for a comment so I figured I'd just answer it anyway so at least the OP got help before it was migrated away. - Gavin Simpson

1 Answers

5
votes

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.