## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>",
                      fig.width = 7, fig.height = 5)
set.seed(20260821)
library(metaGLMM)

## ----fit----------------------------------------------------------------------
dat <- data.frame(
  study = paste0("Study ", 1:8),
  estimate = c(-0.80, -0.30, 0.10, 0.70, 1.10, -0.50, 0.40, 1.30),
  vi = c(0.04, 0.05, 0.03, 0.06, 0.04, 0.05, 0.03, 0.05),
  ni = c(100, 90, 120, 80, 110, 95, 130, 85)
)

fit <- metaGLMM(
  estimate ~ 1,
  data = dat,
  vi = dat$vi,
  ni = dat$ni,
  tau2 = NA,
  tau2_var = TRUE,
  family = gaussian(link = "identity"),
  fast = TRUE
)
stopifnot(is.finite(fit$tau), fit$tau > 0)

## ----prediction---------------------------------------------------------------
pred_conf <- predict(fit, type = "link", interval = "confidence")
pred_pred <- predict(fit, type = "link", interval = "prediction",
                     random_scale = 1)
pred_response <- predict(fit, type = "response", interval = "confidence")

pred_conf
pred_pred
pred_response
stopifnot(diff(as.numeric(pred_pred[1, c("lower", "upper")])) >
            diff(as.numeric(pred_conf[1, c("lower", "upper")])))

## ----contrast-----------------------------------------------------------------
L <- matrix(1, nrow = 1L, ncol = 1L,
            dimnames = list("future study" = "(Intercept)"))
predict(fit, contrast = L, type = "link",
        interval = "prediction", random_scale = 1)

## ----forest-------------------------------------------------------------------
plot_data <- forest(
  fit,
  estimate = dat$estimate,
  vi = dat$vi,
  labels = dat$study,
  parm = "(Intercept)",
  ci_methods = c("wald", "profile", "SBC"),
  ci_args = list(renge.c = 10, silent = TRUE),
  xlab = "Effect estimate"
)
plot_data[plot_data$kind != "study", ]

## ----plot-method--------------------------------------------------------------
plot(fit, type = "forest",
     estimate = dat$estimate,
     vi = dat$vi,
     labels = dat$study,
     parm = "(Intercept)",
     ci_methods = c("wald", "profile", "SBC"),
     ci_args = list(renge.c = 10, silent = TRUE),
     xlab = "Effect estimate")

## ----exchange-----------------------------------------------------------------
exchange_dat <- as_metafor_data(fit)
stopifnot(is.data.frame(exchange_dat))
head(exchange_dat[c("yi", "vi", "slab")])

