From Fabbe’s R tool box: Mixed model regression analysis of a longitudinal two (or more) group design with a nice graph

In the following example we will fit a mixed model regression analysis. In our design we have time as one independent variable, Responder status as another independent variable and we have a dependent variable, the outcome, that we believe is affected by both time and Responder status. In our model we assume that individual trajectories vary over time (the random effect in our model, so called random slope).


# The mixed model we want to fit: 
summary(model.responsegroups <- lme(Outcome_ ~ 
                                    time + Responders + time : Responders, 
                                    random = ~1+time|ID, 
                                    data = yourdata, 
                                    na.action = na.exclude, 
                                    method = "ML"))

# We like to see pairwise comparisons between timepoints and respondergroups as well as point estimates:
lsmeans(model.responsegroups, 
  pairwise~time + Responders + time : Responders, 
  adjust="tukey")

# Now, lets try to plot this
# Create a data frame that ggplot can work with 
d2 <- summary(lsmeans(model.responsegroups, 
  ~ time + Responders + time : Responders))

# Paint your picture (as it will say more than 1.000 words)
graph2 <- ggplot(d2, aes(time)) +
  geom_path(aes(y = lsmean, group = Responders, color = Responders), size = 1.2) +
  geom_errorbar(aes(ymin = lower.CL, ymax = upper.CL), width = 0.05) +
  geom_point(aes(y = lsmean, color = Responders, 
                 shape = Responders), size = 3, shape = 21, fill = "white") +
  labs(x = " ", y = "X") + 
  theme_light()

# Add some explanatory labels to the x-axis and move the legend around:
graph2 <- graph2 + scale_x_discrete(breaks=c("0", "1", "2", "3"),
                      labels=c("Pre treatment", "Post treatment", "follow-up 1", "follow-up 1")) + 
  theme(legend.position = c(0.15, 0.2)) 

# Look what you have done: Beautiful! 
graph2

The code above will provide you with the mixed model regression analysis, point estimates, pairwise comparisons and this graph:

Hope this was helpful. Let me know if it worked! 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s