[英]Using predict on lm list with confidence interval
I have a linear model fitted to a grouped data which generates a list of objects of type lm. 我有一个适合于分组数据的线性模型,该模型生成了lm类型的对象列表。 I want to use this linear model to predict the value of y at a given x with a given confidence interval.
我想使用此线性模型来预测给定x在给定置信区间下的y值。 I want a unique prediction for variable w.
我想要变量w的唯一预测。 Here is the code with sample data:
这是带有示例数据的代码:
x<-c(.34,.355,.37,.385,.34,.355,.37,.385,.34,.355,.37,.385,.34,.355,.37,.385)
y<-c(40,35,28,25,42,36,29,25,44,37,26,23,46,37,33,27)
w<-c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4)
data<-data.frame(x,y,w)
ggplot(data=data,aes(x=x,y=log10(y),color=factor(w)))+
geom_point(size=4)+
geom_smooth(method=lm,aes(group=w,fill=factor(w)),fullrange=TRUE)+
facet_wrap(~w,nrow=2)+
scale_x_continuous(limit=c(.33,.5))
mod <- dlply(data, .(w), function(df) lm(log(y)~x, data = df))
I am trying to use the function predict but it does not work on list. 我正在尝试使用预测功能,但无法在列表中使用。 So I can predict on an element of list
所以我可以预测一个列表元素
newdata<-data.frame(x=.5)
predict(mod[[1]],newdata,interval="confidence")
which gives the following output 它给出以下输出
fit lwr upr
1 0.8476424 0.5981407 1.097144
However, I want to be able to apply predict on each element of the list. 但是,我希望能够对列表的每个元素应用预测。 I tried to use library
nlme
to do the following but it does not give the confidence interval. 我尝试使用库
nlme
进行以下操作,但它没有给出置信区间。
library(nlme)
ll=lmList(log10(y)~x|w,data = data)
predict(ll,newdata,interval="confidence")
output: 输出:
1 2 3 4
0.8476424 0.8042928 0.5818862 0.8633285
I used ggplot2 just for visual aid but I need the actual values at the boundary of the confidence interval to compute the range of predicted y
variable. 我仅将ggplot2用于视觉辅助,但是我需要在置信区间的边界处使用实际值来计算预测的
y
变量的范围。
If you are wanting to apply
on each element of a list, lapply
(list apply) is the way to go: 如果要
apply
列表的每个元素,则可以使用lapply
(列表应用):
do.call(rbind, lapply(mod, function(x) predict(x, newdata, interval="confidence")))
fit lwr upr
1 1.951769 1.3772699 2.526268
1 1.851953 1.4852869 2.218618
1 1.339843 0.1453728 2.534312
1 1.987887 1.4446006 2.531174
so using lapply
, we are running our anonymous function predict(x, newdata, interval="confidence"))
with x being each element of mod. 因此,使用
lapply
,我们正在运行匿名函数predict(x, newdata, interval="confidence"))
其中x是mod的每个元素。 The do.call turns the list output into a nicer matrix. do.call将列表输出转换为更好的矩阵。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.