I am trying to plot an interaction between two continuous variables in R. However, my data is multilevel (people nested within days) so I need to account for the nested structure of my data when I am graphing it. I analyze my data using the lme4 library to account for the nested structure, but I'm having a hard time figuring out how to graph it.
## example data
spin = runif(600, 1, 24)
reg = runif(600, 1, 15)
ID = rep(c("1","2","3","4","5", "6", "7", "8", "9", "10"))
day = rep(1:30, each = 10)
testdata <- data.frame(
spin, reg, ID, day)
testdata$fatigue <- testdata$spin*testdata$reg/10*rnorm(30, mean=3, sd=2)
Here I have my independent variables of spin and reg, dependent variable of fatigue, and people (ID) nested within days. I run my model below.
## running my multilevel model with lme4
library(lme4)
m1 <- lmer(fatigue ~ spin * reg + ( 1 | ID), data = testdata, REML = T)
(m1)
confint(m1, test = "Chisq")
Let's assume I have an interaction between spin and reg. I need to put my continuous variable into a categorical variable in order to plot it.
So I create categorical variable based on one of my continuous variables. Here I pick spin. Note: not sure if this code below is quite right for what I want. Might have to do standard error? Also doesn't take my nested data structure into account, but not sure what to do otherwise.
x <- mean(testdata$spin, na.rm = T)
print(x)
y <- sd(testdata$spin, na.rm = T)
print(y)
testdata$SpinLevel[testdata$spin > x+y] <- "High"
testdata$SpinLevel[testdata$spin > x-y & testdata$spin <= x+y] <- "Mean"
testdata$SpinLevel[testdata$spin <= x-y] <- "Low"
rm(x,y)
Based on what I've found online, I can create a basic plot to show effects. BUT doesn't take nested structure into account (people -- the variable IDs-- are nested within days).
library(ggplot2)
ggplot(testdata,aes(reg,fatigue,linetype=SpinLevel))+
geom_smooth(method="lm",se=FALSE)
This ggplot is good for interpreting the basic effect, but the lines are likely skewed because they don't take my nested structure of my data into account (people within days).
I can also graph my model with the effects library. This DOES take nested structure into account. Except the graph is not pretty and is in quartiles, and is very difficult to interpret. I would like it to be by high, mean, and low and all on the same graph. But I'm not sure how to do this.
library(effects)
plot(effect("spin*reg", m1), grid=TRUE, labels = T,
xlevels=list(spin=quantile(testdata$spin, seq(0, 1, 0.25))))
Any ideas? Would be much appreciated.