plot interaction terms in a mixed-model - r

I would like to visualize the effect of a significant interaction term in the following mixed effects model.
c1 <- lmer(log.weight ~ time + I(time^2) + temp + precip + time:precip + time:temp + (1|indiv), data = noctrl)
This model includes fixed effects of 'time' (simple and quadratic term), 'temperature', 'precipitation' and two interactions on the logarithmized response 'weight'. All terms are significant and the models assumptions of normality and homogeneity are met.
I’ve been using the 'effects' package to produce interaction plots to show the effect of the interactions. When I try to show the interaction of time and temperature (time:temp) with the following code I’m not sure whether the resulting plot correctly shows this interaction.
ef2 <- effect(term="time:temp", c1, multiline=TRUE)
y <- as.data.frame(ef2)
ggplot(y , aes(time, fit, color=temp)) + geom_point() + geom_errorbar(aes(ymin=fit-se, ymax=fit+se), width=0.4)
I need help understanding the resulting plot please. How come despite this interaction term is highly significant, the SEs overlap at each value of x?
Am I using the effects package correctly? Or is it because I need to include the quadratic term of time I(time^2) in the interaction terms as well?
Thank you very much for the clarification.

Related

plotting effect of the interaction between 2 explanatory variables on the response variable from a generalized linear mixed effect model (glmer) in R

I have the following code
glmer(Success ~ Trial*Treatment + 1|ID + Origin + Shelter, family = binomial, data = rama)
It gives me a significant effect of the interaction between Trial and Treatment on the response variable success.
I would like to plot this interaction.
I tried to use
plot(Success ~ Trial*Treatment, data = rama)
But it doesn't plot the interaction, rather makes two different plots, one Success vs Trial and another Success vs Treatment.
Ideally, I would like to merge these two graphs, a bit as what I would get if it was an LME instead of a GLME and I plotted (if success was a continuous variable) and I'd use the following code
boxplot(Success ~ Trial*Treatment, data = rama)
I would be super happy if anyone has an idea.
Thanks a lot!

Plotting Marginal effects of interactions with continuous and dummy

I have a doubt about my homework on how to plot multiple interactions and I would be very grateful if anyone could help. I know this is a popular topic, but I have not seen questions addressing my specific problem. I hope is not a repetition
I have a model with 3 explanatory variables and two interactions. Two variables are continuous and one is a dummy. I would like to plot into a single image the marginal effect of the three interactions.
the model is something like this
y = a+ b_1c1 + b_2c2 + b_3d + b_4c1c2 + b_5c1d
In sum, I have one continuous variable (c1), that is interacted both with the other continuous variable (c2) and the dummy variable (d).
The code below uses data from the MASS package to allow a reproducible example.
library(interplot)
library(MASS) # to take the dataset from
data<- cars93
library(interplot) # for plotting interations
and I create my model
model<- lm(Price ~ Horsepower*EngineSize # c1*c2 interaction
+ Horsepower*Man.trans.avail, #c1*d interaction
data = data)
I would like to plot the estimated effects of the Horsepower on price as a function of the EngineSize for Man.trans.avail=0 (No),
and plot that same conditional effect of Horsepower on price as a function of the EngineSize for Man.trans.avail=1 (Yes). Possibly putting them into the same plot.
Using the interplot function I am able to see the conditional Horsepower on price as a function of the EngineSize but without controlling for Man.trans.avail
interplot(m=model, var1 = "Horsepower", var2 = "EngineSize", hist = TRUE)
The result plots the marginal effect line of Horsepower and EngineSize, however, is not able to plot two lines for different values of Man.trans.avail and I was wondering whether you had some idea on how to plot marginal effects in similar circumstances.
I thank you a lot in advance for your replies

Plotting random slopes from glmer model using sjPlot

In the past, I had used the sjp.glmer from the package sjPlot to visualize the different slopes from a generalized mixed effects model. However, with the new package, I can't figure out how to plot the individual slopes, as in the figure for the probabilities of fixed effects by (random) group level, located here
Here is the code that, I think, should allow for the production of the figure. I just can't seem to get it in the new version of sjPlot.
library(lme4)
library(sjPlot)
data(efc)
# create binary response
efc$hi_qol = 0
efc$hi_qol[efc$quol_5 > mean(efc$quol_5,na.rm=T)] = 1
# prepare group variable
efc$grp = as.factor(efc$e15relat)
# data frame for 2nd fitted model
mydf <- na.omit(data.frame(hi_qol = as.factor(efc$hi_qol),
sex = as.factor(efc$c161sex),
c12hour = as.numeric(efc$c12hour),
neg_c_7 = as.numeric(efc$neg_c_7),
grp = efc$grp))
# fit 2nd model
fit2 <- glmer(hi_qol ~ sex + c12hour + neg_c_7 + (1|grp),
data = mydf,
family = binomial("logit"))
I have tried to graph the model using the following code.
plot_model(fit2,type="re")
plot_model(fit2,type="prob")
plot_model(fit2,type="eff")
I think that I may be missing a flag, but after reading through the documentation, I can't find out what that flag may be.
Looks like this might do what you want:
(pp <- plot_model(fit2,type="pred",
terms=c("c12hour","grp"),pred.type="re"))
type="pred": plot predicted values
terms=c("c12hour", "grp"): include c12hour (as the x-axis variable) and grp in the predictions
pred.type="re": random effects
I haven't been able to get confidence-interval ribbons yet (tried ci.lvl=0.9, but no luck ...)
pp+facet_wrap(~group) comes closer to the plot shown in the linked blog post (each random-effects level gets its own facet ...)
Ben already posted the correct answer. sjPlot uses the ggeffects-package for marginal effects plot, so an alternative would be using ggeffects directly:
ggpredict(fit2, terms = c("c12hour", "grp"), type="re") %>% plot()
There's a new vignette describing how to get marginal effects for mixed models / random effects. However, confidence intervals are currently not available for this plot-type.
The type = "ri.prob" option in the linked blog-post did not adjust for covariates, that's why I first removed that option and later re-implemented it (correctly) in ggeffects / sjPlot. The confidence intervals shown in the linked blog-post are not correct, either. Once I figure out a way how to obtain CI or prediction intervals, I'll add this option as well.

plot - How to plot interaction of logistic regression model (glm) with multiple imputed data (MICE)?

I created an interaction term with iv*sex and imputed the data with mice. Then used the imputed data to run a logistic regression model (glm):
model <- with(data=imp, glm(dv~control+iv+sex+iv*sex, family="binomial"))
The following are the abbreviations of the variable names:
dependent variable=dv, independent variable=iv, moderator=sex, interaction term= iv*sex
There is significant interaction for iv*sex and I would like to plot a graph for the interaction but I couldn't find how to. It will be greatly appreciated if any solutions is offered. Thanks!
I've just run into the same issue, and with effects package I solved it.
e <- effects::effect("iv*sex", model)
e <- as.data.frame(e)
ggplot2::ggplot(e, ggplot2::aes(iv, fit, color=sex, group = sex)) +
ggplot2::geom_point() +
ggplot2::geom_line() +
"fit" is your dependent variable, in your case "dv".

Mixed Modelling - Different Results between lme and lmer functions

I am currently working through Andy Field's book, Discovering Statistics Using R. Chapter 14 is on Mixed Modelling and he uses the lme function from the nlme package.
The model he creates, using speed dating data, is such:
speedDateModel <- lme(dateRating ~ looks + personality +
gender + looks:gender + personality:gender +
looks:personality,
random = ~1|participant/looks/personality)
I tried to recreate a similar model using the lmer function from the lme4 package; however, my results are different. I thought I had the proper syntax, but maybe not?
speedDateModel.2 <- lmer(dateRating ~ looks + personality + gender +
looks:gender + personality:gender +
(1|participant) + (1|looks) + (1|personality),
data = speedData, REML = FALSE)
Also, when I run the coefficients of these models I notice that it only produces random intercepts for each participant. I was trying to then create a model that produces both random intercepts and slopes. I can't seem to get the syntax correct for either function to do this. Any help would be greatly appreciated.
The only difference between the lme and the corresponding lmer formula should be that the random and fixed components are aggregated into a single formula:
dateRating ~ looks + personality +
gender + looks:gender + personality:gender +
looks:personality+ (1|participant/looks/personality)
using (1|participant) + (1|looks) + (1|personality) is only equivalent if looks and personality have unique values at each nested level.
It's not clear what continuous variable you want to define your slopes: if you have a continuous variable x and groups g, then (x|g) or equivalently (1+x|g) will give you a random-slopes model (x should also be included in the fixed-effects part of the model, i.e. the full formula should be y~x+(x|g) ...)
update: I got the data, or rather a script file that allows one to reconstruct the data, from here. Field makes a common mistake in his book, which I have made several times in the past: since there is only a single observation in the data set for each participant/looks/personality combination, the three-way interaction has one level per observation. In a linear mixed model, this means the variance at the lowest level of nesting will be confounded with the residual variance.
You can see this in two ways:
lme appears to fit the model just fine, but if you try to calculate confidence intervals via intervals(), you get
intervals(speedDateModel)
## Error in intervals.lme(speedDateModel) :
## cannot get confidence intervals on var-cov components:
## Non-positive definite approximate variance-covariance
If you try this with lmer you get:
## Error: number of levels of each grouping factor
## must be < number of observations
In both cases, this is a clue that something's wrong. (You can overcome this in lmer if you really want to: see ?lmerControl.)
If we leave out the lowest grouping level, everything works fine:
sd2 <- lmer(dateRating ~ looks + personality +
gender + looks:gender + personality:gender +
looks:personality+
(1|participant/looks),
data=speedData)
Compare lmer and lme fixed effects:
all.equal(fixef(sd2),fixef(speedDateModel)) ## TRUE
The starling example here gives another example and further explanation of this issue.

Resources