You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggcoef_model绘制含两个随机截距的glmmTMB模型时报错

问题描述

使用GGally包绘制包含2个及以上随机效应项的glmmTMB模型条件固定效应图时,会触发如下报错:

调用tidy_fun()时发生错误。最可能的原因是tidy_fun=参数传入的函数存在拼写错误、不存在、与目标对象不兼容,或缺少必要参数(例如conf.level=或conf.int=)。底层错误信息如下:
Error: Error in stop_vctrs():
! Can't recycle ..1 (size 3) to match ..2 (size 2).

经排查,该问题仅在模型纳入多个随机效应项时触发,仅含单个随机效应项的同结构模型可正常绘图。直接调用broom.mixed::tidy提取系数结果后传入绘图函数的常规尝试无法解决该问题。

复现代码
# 调用内置randu数据集
data(randu)
randu$A <- factor(rep(c(1,2), 200))
randu$B <- factor(rep(c(1,2,3,4), 100))

# 拟合含两个随机效应项的glmmTMB模型
test <- glmmTMB(y ~ x + z + (0 +x|A) + (1|B), family="gaussian", data=randu)

# 以下调用均会触发报错
ggcoef_model(test)
ggcoef_model(test, tidy_fun = broom.mixed::tidy)
ggcoef_model(test, tidy_fun = broom.mixed::tidy, conf.int = TRUE, intercept=FALSE)
# 注意:该行写法本身存在参数错误,tidy_fun需要传入函数对象,而非函数执行后返回的数据框
ggcoef_model(test, tidy_fun = broom.mixed::tidy(test, effects="fixed", component = "cond", conf.int = TRUE))
报错原因

ggcoef_model默认调用的tidy泛型函数处理多随机效应的glmmTMB对象时,会错误将随机效应方差成分的统计结果与固定效应结果做列绑定,两个结果集行数不一致,触发vctrs包的长度回收校验报错。

可行解决方案

自定义包装后的tidy函数,显式限定仅提取条件模型的固定效应部分,避免混入随机效应相关结果,再将自定义函数传入tidy_fun参数即可:

library(GGally)
library(glmmTMB)
library(broom.mixed)

# 自定义适配的tidy函数
tidy_fixed <- function(model, ...) {
  broom.mixed::tidy(
    model,
    effects = "fixed",
    component = "cond",
    conf.int = TRUE,
    ...
  )
}

# 正常绘图
ggcoef_model(
  test,
  tidy_fun = tidy_fixed,
  intercept = FALSE # 按需求选择是否展示截距
)

如果希望手动提前整理好绘图数据再传入,需使用ggcoef()而非ggcoef_model(),该函数支持直接接收整理好的系数数据框作为输入:

# 提前提取固定效应结果
tidy_res <- broom.mixed::tidy(
  test,
  effects = "fixed",
  component = "cond",
  conf.int = TRUE
)

# 直接传入数据框绘图
ggcoef(tidy_res, intercept = FALSE)

内容的提问来源于stack exchange,提问作者Charlie_J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 07:54:25