I was fitting a mixed model with random intercept and random slope for longitudinal data using the nlme package in R, similar to the model below (using an artificial and very small dataset for illustration, but the types of variables are similar):
set.seed(1)
Sex = sample(rep(c(0,1), times = 50))
set.seed(2)
BT = sample(rep(c(0,1), times = 50))
AT = abs(round(rnorm(100, 6.5, 4),0))
Age = abs(round(rnorm(100, 3.8, 2),2))
outcome <- abs(round(rnorm(100, 85, 10), 0))
ID <- seq(1,100)
data <- data.frame(ID = ID, Sex = Sex,Age = Age, BT = BT, AT = AT, outcome = outcome)
ids_list <- list()
ids <- seq(1,100)
set.seed(1)
reps <- sample(rep(2:5, each = 25))
for (i in 1:length(ids)){
ids_list[[i]] <- rep(i, each = reps[i])
}
time_list <- list()
for (i in 1:length(ids)){
time_list[[i]] <- sort(round(runif(reps[i], 0, 15),0), decreasing = F)
}
new_df <- data.frame(ID = unlist(ids_list), Time = unlist(time_list))
df <- merge(data, new_df, by = "ID")
> head(df)
ID Sex Age BT AT outcome Time
1 1 1 0.40 0 5 90 4
2 1 1 0.40 0 5 90 4
3 1 1 0.40 0 5 90 9
4 1 1 0.40 0 5 90 10
5 2 0 1.32 0 7 90 3
6 2 0 1.32 0 7 90 7
model <- lme(outcome ~ Sex + BT + Age + AT*Time, random = ~ 1 + Time|ID,
data = df, na.action = na.exclude, method = "REML")
which I wanted to visualise using ggpredict
in the ggeffects
package. Unfortunately, when using ggpredict,
ggpredict(model, terms = c("AT", "Time"), type = "re")
I get the following:
# Predicted values of outcome
Error in tapply(x$predicted, list(x$group), NULL) :
arguments must have same length
Using other variables to display (in this case, e.g. BT is a factor), I get the same error.
Using the lme4 package and fitting the same model with lmer()
, it does work (however I would like to use the nlme package, which is supported by ggeffects
if I am not mistaken). So far, reading the vignette and googling haven't helped me fix the problem unfortunately.