R:绘制时间变量的预测和实际响应

时间:2018-01-30 18:53:02

标签: r ggplot2 survival-analysis

我有一个模型,我想在时间变量上绘制预测。在同一图表中添加该时间点的平均响应也非常有用。

这是一些可重现的数据。

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

任何提示或想法?

编辑:谢谢你的回复!是的我知道在这个例子中时间不在模型中。我只是想做一个简单的例子。在我的真实模型中,包括时间。是的,我想绘制平均响应和平均预测值。

2 个答案:

答案 0 :(得分:1)

您根据x1x2而非时间进行预测,因此每次都会有多个预测。如果你想每次绘制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)

对我而言,这似乎是一件奇怪的事情,没有在模型中加入时间。下面是一种方法,计算x的平均值和预测的平均值。

library(tidyverse)

df$pred <- predict(fit)

means <- df %>% 
  group_by(time) %>% 
  summarize(mean_y = mean(y),
            mean_pred = mean(pred)) %>% 
  gather(mean, val, -time)

ggplot(means, aes(time, val, color = mean)) +
  geom_point() +
  geom_line()

enter image description here