easystats / insight

:crystal_ball: Easy access to model information for various model objects
https://easystats.github.io/insight/
GNU General Public License v3.0
380 stars 38 forks source link

`null_model()` for zero-inflated models. #891

Closed strengejacke closed 2 weeks ago

strengejacke commented 2 weeks ago

Presumably it would be

formula = count ~ 1 + (1 | persons),
 ziformula =    ~1 + (1 | persons)

?

Originally posted by @bbolker in https://github.com/easystats/insight/issues/889#issuecomment-2168086084

strengejacke commented 2 weeks ago

This code might work:

data(fish, package = "insight")
m1 <- glmmTMB::glmmTMB(
  count ~ child + camper + (1 | persons),
  ziformula = ~ child + camper + (1 | persons),
  data = fish,
  family = poisson()
)

args <- lapply(insight::get_call(m1), deparse)[-1]
formula_args <- endsWith(names(args), "formula")

resp <- insight::find_response(m1)
args[formula_args] <- lapply(names(args[formula_args]), function(f_names) {
  f <- args[[f_names]]
  re_string <- sapply(insight:::.findbars(stats::as.formula(f)), insight::safe_deparse)
  if (!insight::is_empty_object(re_string)) {
    if (startsWith(f_names, "zi")) {
      stats::reformulate(paste0("(", re_string, ")"), response = NULL)
    } else {
      stats::reformulate(paste0("(", re_string, ")"), response = resp)
    }
  } else {
    stats::as.formula(f)
  }
})

args[!formula_args] <- lapply(args[!formula_args], str2lang)
args
#> $formula
#> count ~ (1 | persons)
#> <environment: 0x0000022c396853f8>
#> 
#> $data
#> fish
#> 
#> $family
#> poisson()
#> 
#> $ziformula
#> ~(1 | persons)
#> <environment: 0x0000022c3965f588>
#> 
#> $dispformula
#> ~1
#> <environment: 0x0000022c39118cf8>

do.call(glmmTMB::glmmTMB, args)
#> Formula:          count ~ (1 | persons)
#> Zero inflation:         ~(1 | persons)
#> Data: fish
#>       AIC       BIC    logLik  df.resid 
#> 1880.6558 1894.7417 -936.3279       246 
#> Random-effects (co)variances:
#> 
#> Conditional model:
#>  Groups  Name        Std.Dev.
#>  persons (Intercept) 0.8114  
#> 
#> Zero-inflation model:
#>  Groups  Name        Std.Dev.
#>  persons (Intercept) 8.98e-05
#> 
#> Number of obs: 250 / Conditional model: persons, 4 / Zero-inflation model: persons, 4
#> 
#> Fixed Effects:
#> 
#> Conditional model:
#> (Intercept)  
#>       1.599  
#> 
#> Zero-inflation model:
#> (Intercept)  
#>      0.1763

Created on 2024-06-14 with reprex v2.1.0

bwiernik commented 2 weeks ago

Lgtm