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

如何在嵌套数据框中使用MuMIn::dredge处理glmmTMB模型(含并行)

嵌套数据框中使用dredge处理glmmTMB模型的问题及解决方案

我在嵌套数据框中存储了多个glmmTMB模型,想要迭代使用dredge函数,但即使处理单个模型也会报错:

Error in eval(call("is.data.frame", gmCall$data), gmEnv) :
object '"is.data.frame"' not found

只有当模型在嵌套数据框外构建,且数据作为环境中的独立对象存储时,dredge才能正常运行。我不想创建大量独立的数据框和模型,想请教是否有办法在嵌套数据框中使用该函数,或者改用列表实现?


示例代码(基于mtcars数据集)

# 定义模型拟合函数
mod_fx <- function(x) {
  glmmTMB(mpg ~ disp + drat + wt, 
          data = x,
          family = gaussian(),
          na.action = "na.fail")
}

# 分组并嵌套数据
dat <- mtcars %>% 
  group_by(cyl) %>%
  nest() %>% 
  mutate(mod = map(data, mod_fx))

# 模型摘要正常,但注意数据显示为x
summary(dat$mod[[1]])

# 运行dredge报错
dred_dat <- dredge(dat$mod[[1]],
                   rank = "AICc",
                   evaluate = T)

# 当数据作为独立对象存储时,dredge正常运行
dat2 <- filter(mtcars, cyl == 6)

m1 <- glmmTMB(mpg ~ disp + drat + wt, 
        data = dat2,
        family = gaussian(),
        na.action = "na.fail")

summary(m1) # 模型结果一致,dredge可正常运行:

dred_dat <- dredge(m1,
                   rank = "AICc",
                   evaluate = T)

# 直接使用filter结果作为数据输入时,dredge同样报错
m3 <- glmmTMB(mpg ~ disp + drat + wt, 
              data = filter(mtcars, cyl == 6),
              family = gaussian(),
              na.action = "na.fail")

summary(m3) # 数据显示为filter(mtcars, cyl == 6)

dred_dat <- dredge(m3,
                   rank = "AICc",
                   evaluate = T)
# 报错信息:Error in dredge(m3, rank = "AICc", evaluate = T) : 'global.model' uses "data" that is a function value: use a variable instead

尝试并行处理(失败方案)

clust <- try(makeCluster(detectCores()-1))
invisible(clusterCall(clust, "library", "glmmTMB",
                      character.only = TRUE))

dfun <- function(x) {
  g1 <- glmmTMB(mpg ~ disp + drat + wt, 
                data = x,
                family = gaussian(),
                na.action = "na.fail")
  clusterExport(clust, "data")
  dredge(g1, cluster = clust, rank = "AICc",  evaluate = TRUE)
}

dat <- mtcars %>% 
  group_by(cyl) %>%
  nest() %>% 
  mutate(dredged = map(data, dfun))

并行处理成功方案(使用doParallel)

library(tidyverse)
library(MuMIn)
library(doParallel)

dfun <- function(x) {
  g1 <- glmmTMB(mpg ~ disp + drat + wt, 
                data = x,
                family = gaussian(),
                na.action = "na.fail")
  dredge(g1, rank = "AICc",  evaluate = TRUE)
}

dat <- mtcars %>% 
  group_by(cyl) %>%
  nest()

ncores <- detectCores() - 1L
registerDoParallel(ncores)

dat_dredge <- foreach(i = 1:nrow(dat),
                      .packages = c("MuMIn", "glmmTMB"),
                      .final = function(x) setNames(x, dat$cyl)) %dopar% {
                        dfun(dat$data[[i]])
                      }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:33:42