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

如何将GLMMadaptive拟合的混合模型结果转换为tidy格式对象

解决GLMMadaptive删失正态混合模型无法用tidy函数转换格式的问题

GLMMadaptive包的mixed_model对象目前未被broom包原生支持,因此直接调用tidy()函数无法生成预期的tidy格式结果。以下是两种可行的解决方案:

方案一:手动提取并整理结果

通过直接访问模型摘要的内置元素,将各部分结果转换为tidy格式的数据框:

# 提取固定效应
fixed_effects <- as.data.frame(summary(foo)$fixed)
fixed_effects$term <- rownames(fixed_effects)
rownames(fixed_effects) <- NULL
fixed_effects <- fixed_effects[, c("term", "Estimate", "Std.Err", "z-value", "p-value")]

# 提取随机效应的标准差与相关系数
rand_effects <- as.data.frame(summary(foo)$D)
rand_effects$term <- rownames(rand_effects)
rownames(rand_effects) <- NULL
colnames(rand_effects) <- c("StdDev", "Corr", "term")

# 提取残差标准差的对数估计
resid_sigma <- as.data.frame(summary(foo)$sigma)
resid_sigma$term <- "log(residual std. dev.)"
rownames(resid_sigma) <- NULL
colnames(resid_sigma) <- c("Estimate", "Std.Err", "term")

执行后,fixed_effects、rand_effects、resid_sigma分别为对应部分的tidy格式数据框。

方案二:自定义broom的tidy方法

如果需要频繁使用tidy()函数处理该类模型,可以自定义针对mixed_model类的tidy方法:

library(broom)

# 为mixed_model类编写tidy方法
tidy.mixed_model <- function(x, type = c("fixed", "random", "sigma"), ...) {
  type <- match.arg(type)
  
  if (type == "fixed") {
    fixed <- as.data.frame(summary(x)$fixed)
    fixed$term <- rownames(fixed)
    rownames(fixed) <- NULL
    fixed <- fixed[, c("term", "Estimate", "Std.Err", "z-value", "p-value")]
    class(fixed) <- c("tbl_df", "tbl", "data.frame")
    return(fixed)
  } else if (type == "random") {
    rand <- as.data.frame(summary(x)$D)
    rand$term <- rownames(rand)
    rownames(rand) <- NULL
    colnames(rand) <- c("StdDev", "Corr", "term")
    class(rand) <- c("tbl_df", "tbl", "data.frame")
    return(rand)
  } else if (type == "sigma") {
    sigma <- as.data.frame(summary(x)$sigma)
    sigma$term <- "log(residual std. dev.)"
    rownames(sigma) <- NULL
    colnames(sigma) <- c("Estimate", "Std.Err", "term")
    class(sigma) <- c("tbl_df", "tbl", "data.frame")
    return(sigma)
  }
}

# 调用示例
tidy(foo, type = "fixed")  # 获取固定效应的tidy结果
tidy(foo, type = "random") # 获取随机效应的tidy结果
tidy(foo, type = "sigma")  # 获取残差标准差的tidy结果

自定义方法后,即可通过指定type参数,用tidy()直接提取对应部分的tidy格式数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 08:10:34