tests/testthat/test-cluster_map.R

test_that("cluster_map works with basic internal polygons", {


  # Create dummy data with 10 simple polygons
  set.seed(123)
  dummy_data <- data.frame(
    district_code = 1:10,
    household_wealth = sample(1:5, 10, replace = TRUE)
  )

  # Generate simple polygon geometries for the geometry column
  dummy_data$geometry <- sf::st_sfc(lapply(1:10, function(x) {
    sf::st_polygon(list(matrix(c(0, 0, 1, 0, 1, 1, 0, 1, 0, 0) + x, ncol = 2, byrow = TRUE)))
  }))

  # Convert the dataframe to an sf object
  dummy_data <- sf::st_as_sf(dummy_data)

  # Create a spatial weights object (listw)
  coords <- sf::st_centroid(sf::st_geometry(dummy_data))
  coords <- sf::st_coordinates(coords)
  distances <- as.matrix(dist(coords))
  weights <- exp(-distances / 0.2)
  diag(weights) <- 0

  # Handle zero sum general weights warning by ensuring no row sums to zero
  if (any(rowSums(weights) == 0)) {
    weights[rowSums(weights) == 0, ] <- 1
  }

  # Suppress warnings while generating listw
  listw <- suppressWarnings(spdep::mat2listw(weights, style = "W"))

  # Run Spdeplisa to calculate Local Moran's I and sign combinations
  lisa_result <- Spdeplisa(dummy_data, "household_wealth", listw)

  # Ensure the result is an sf object (retain geometry)
  lisa_result <- sf::st_as_sf(lisa_result)

  # Suppress warnings while running cluster_map
  result <- suppressWarnings(cluster_map(
    dataset = lisa_result,
    lisa_value = "lisa_I",
    lisa_label = "sign_combination3",
    label = "High-High",
    lisa_cutoff = 0,  # No cutoff to avoid issues
    location_var = "district_code",
    location_name = "district_code",
    level2 = "district_code"  # Set level2 to be the same as location_var
  ))

  # Assertions to check the outputs
  expect_s3_class(result$dataset_with_clusters, "sf")
  expect_s3_class(result$plot, "ggplot")
  expect_true(nrow(result$dataset_with_clusters) > 0)
})

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.