简体   繁体   English

如何根据线性模型在r中创建置信区间?

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

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. 我想创建一个y vs x的线性模型,并使用它为给定的x观测值找到y的置信区间。

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? 当x = 2时,如何使其仅返回y的一个置信区间?

You need: 你需要:

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

for reasons that are clear when you look at ?predict.lm . 由于当您查看?predict.lm时显而易见的原因。

The newdata argument is required to be a data frame. newdata参数必须是数据帧。 You supplied a length 1 vector. 您提供了长度为1的向量。 Secondly, because of the way S3 methods work, what you thought you were passing to newdata was actually not passed to newdata at all. 其次,由于S3方法的工作方式,您认为传递给newdata实际上根本没有传递给newdata You actually specified a new argument x with value 2 , which predict() promptly forgot about (it got mopped up by the ... argument). 您实际上指定了一个新的参数x ,其值为2predict()立即忘记了该参数(它被...参数擦掉了)。 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. 如果未提供newdata ,则predict()使用存储在拟合模型对象( bbbb )中的数据,并返回拟合值以及任何请求的附加值,例如CI,标准错误等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM