我有一个模型,我想在时间变量上绘制预测。在同一图表中添加该时间点的平均响应也非常有用。
这是一些可重现的数据。
set.seed(123)
x1 = rnorm(1000) # some continuous variables
x2 = rnorm(1000)
z = 1 + 2*x1 + 3*x2 # linear combination with a bias
pr = 1/(1+exp(-z)) # pass through an inv-logit function
y = rbinom(1000,1,pr) # bernoulli response variable
#valid glm:
df = data.frame(y=y,x1=x1,x2=x2,time=rep(seq(1:10),10))
fit = glm( y~x1+x2,data=df,family="binomial")
现在,我希望小组mean(predict(fit,df,type="response"))
以及小组time
mean(y)
绘制time
。
任何提示或想法?
编辑:谢谢你的回复!是的我知道在这个例子中时间不在模型中。我只是想做一个简单的例子。在我的真实模型中,包括时间。是的,我想绘制平均响应和平均预测值。答案 0 :(得分:1)
您根据x1
和x2
而非时间进行预测,因此每次都会有多个预测。如果你想每次绘制mean(y)
和每次平均预测y
(红色)你可以做
require(dplyr);require(reshape2);require(ggplot2)
df %>%
mutate(pred = predict(fit, df, type="response")) %>%
group_by(time) %>%
summarize_at(vars(y, pred), mean) %>%
melt(id = 'time') %>%
ggplot(aes(time, value, color = variable)) + geom_line()
答案 1 :(得分:1)