使用nlme的lme模型调用ggpredict报错,lmer模型正常运行
nlme::lme模型使用ggeffects::ggpredict时出现"arguments must have same length"错误的解决办法
问题重现
使用nlme拟合含随机截距和斜率的混合模型:
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") model <- lme(outcome ~ Sex + BT + Age + AT*Time, random = ~ 1 + Time|ID, data = df, na.action = na.exclude, method = "REML")
调用ggpredict(model, terms = c("AT", "Time"), type = "re")时触发错误:
Error in tapply(x$predicted, list(x$group), NULL) : arguments must have same length
更换其他变量仍报错,但lme4::lmer拟合的模型可正常使用ggpredict。
解决方法
1. 移除数据中的重复观测
你的数据集df存在同一ID-Time组合的重复行(比如ID=1的Time=4出现两次),这是导致ggpredict处理随机效应分组时长度不匹配的核心原因。先去重后重新拟合模型:
# 去重:保留每个ID-Time的唯一行 df_clean <- df[!duplicated(df[, c("ID", "Time")]), ] # 重新拟合模型 model_clean <- lme(outcome ~ Sex + BT + Age + AT*Time, random = ~ 1 + Time|ID, data = df_clean, na.action = na.exclude, method = "REML") # 重新运行ggpredict ggpredict(model_clean, terms = c("AT", "Time"), type = "re")
2. 手动计算随机效应预测值并可视化
如果去重不符合分析需求,可手动构建预测网格,结合predict.lme()计算预测值后用ggplot可视化:
library(ggplot2) # 创建预测网格:选取AT的分位数、Time的全范围,其他协变量取均值/众数 pred_grid <- expand.grid( AT = quantile(df$AT, c(0.25, 0.5, 0.75)), Time = seq(min(df$Time), max(df$Time), by = 1), Sex = round(mean(df$Sex)), BT = round(mean(df$BT)), Age = mean(df$Age), ID = unique(df$ID) # 包含所有个体以计算随机效应 ) # 计算含随机效应的预测值(level=1表示个体水平) pred_grid$predicted <- predict(model, newdata = pred_grid, level = 1) # 绘制可视化图 ggplot(pred_grid, aes(x = Time, y = predicted, color = factor(AT))) + geom_line(aes(group = interaction(AT, ID)), alpha = 0.3) + # 个体趋势线 stat_summary(aes(group = AT), fun = mean, geom = "line", size = 1.2) + # 平均趋势线 labs(x = "Time", y = "Predicted Outcome", color = "AT") + theme_minimal()
3. 转换nlme模型为lmer对象(临时方案)
若需快速复用ggpredict的功能,可使用nlme4lmer包将lme模型转换为lmer对象:
library(nlme4lmer) model_lmer <- as_lmer(model) ggpredict(model_lmer, terms = c("AT", "Time"), type = "re")
内容的提问来源于stack exchange,提问作者yentl02
相关产品推荐
相关产品推荐

