tests/testthat/test-prop_svyglm.R

test_that("final_prop_svyglm runs on synthetic data and returns OR table and AUC", {

  set.seed(123)
  n <- 800

  synthetic_svy <- data.frame(
    psu      = sample(1:80, n, replace = TRUE),
    strata   = sample(1:40, n, replace = TRUE),
    weight   = runif(n, 0.5, 3),
    exposure = rbinom(n, 1, 0.45),
    age      = round(rnorm(n, 50, 12)),
    sex      = factor(sample(c("Male", "Female"), n, replace = TRUE)),
    bmi      = round(rnorm(n, 27, 4), 1)
  )

  linpred <- -2 + 0.8 * synthetic_svy$exposure + 0.03 * synthetic_svy$age
  synthetic_svy$outcome <- rbinom(n, 1, plogis(linpred))

  # ---- Fit propensity-weighted model ------------------------------------
  fit_prop <- final_prop_svyglm(
    data        = synthetic_svy,
    dep_var     = "outcome",
    exposure    = "exposure",
    covariates  = c("age", "sex", "bmi"),
    id_var      = "psu",
    strata_var  = "strata",
    weight_var  = "weight"
  )

  ## ---- basic structure --------------------------------------------------
  expect_s3_class(fit_prop, "svyCausal")
  expect_true(is.list(fit_prop))

  ## ---- OR table ---------------------------------------------------------
  expect_true("OR_table" %in% names(fit_prop))
  expect_s3_class(fit_prop$OR_table, "data.frame")

  expect_true(
    all(c("OR", "CI_low", "CI_high") %in% colnames(fit_prop$OR_table))
  )

  expect_true(all(fit_prop$OR_table$OR > 0))



  ## ---- predictions ------------------------------------------------------
  expect_true("predictions" %in% names(fit_prop))
  expect_length(fit_prop$predictions, n)

  ## ---- check OR vs CI ---------------------------------------------------
  expect_true(
    all(
      fit_prop$OR_table$CI_low <= fit_prop$OR_table$OR &
        fit_prop$OR_table$OR <= fit_prop$OR_table$CI_high
    )
  )
})

Try the svyCausalGLM package in your browser

Any scripts or data that you put into this service are public.

svyCausalGLM documentation built on March 3, 2026, 5:08 p.m.