tests/testthat/test-Repglmre2.R

test_that("Repglmre2 runs mixed-effects logistic regression across all locations correctly", {
  # Create dummy data
  set.seed(123)
  dummy_data <- data.frame(
    years_education = rnorm(100, 12, 3),
    gender_female = rbinom(100, 1, 0.5),
    household_wealth = sample(1:5, 100, replace = TRUE),
    district_code = sample(1:10, 100, replace = TRUE),
    HHid = as.character(rep(1:20, each = 5, length.out = 100))
  )

  # Drop the problematic location (e.g., district_code == 4)
  dummy_data <- dummy_data[dummy_data$district_code != 4, ]

  # Create a binary outcome variable for years of education
  dummy_data$education_binary <- ifelse(dummy_data$years_education > 11, 1, 0)

  # Define a logistic regression formula
  formula <- education_binary ~ gender_female + household_wealth:gender_female

  # Run the mixed-effects logistic model across all locations (suppress warnings)
  result <- suppressWarnings(Repglmre2(dummy_data, formula, "district_code", "HHid", family = binomial()))

  # Test if the result contains the expected columns for estimates and std_error
  expect_true(any(grepl("estimate", colnames(result))))
  expect_true(any(grepl("std_error", colnames(result))))

  # Test if the result contains rows for Marginal and Conditional R-squared
  expect_true(any(grepl("Marginal R-squared", colnames(result))))
  expect_true(any(grepl("Conditional R-squared", colnames(result))))

  # Test if the result has the correct number of rows for successfully fitted districts
  expected_rows <- length(unique(dummy_data$district_code))  # All valid districts
  expect_equal(nrow(result), expected_rows)
})

Try the DHSr package in your browser

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

DHSr documentation built on April 4, 2025, 12:18 a.m.