tests/testthat/test-build-neighbors.R

test_that("row-based adaptive neighborhoods select nearest rows", {
  coords <- matrix(
    c(
      0, 0,
      1, 0,
      2, 0
    ),
    ncol = 2,
    byrow = TRUE
  )

  result <- build_neighbors(
    coords = coords,
    focal_index = 1,
    bandwidth = 2,
    adaptive = TRUE,
    neighbor_unit = "row"
  )

  expect_equal(result$neighbor_index, c(1L, 2L))
  expect_equal(result$distances, c(0, 1))
  expect_equal(result$local_bandwidth, 1)
  expect_equal(result$neighbor_unit, "row")
  expect_null(result$neighbor_location_id)
})


test_that("location neighborhoods retain all rows from selected locations", {
  coords <- matrix(
    c(
      0, 0,
      0, 0,
      1, 0,
      1, 0,
      3, 0,
      3, 0
    ),
    ncol = 2,
    byrow = TRUE
  )

  location_id <- c("A", "A", "B", "B", "C", "C")

  result <- build_neighbors(
    coords = coords,
    focal_index = 1,
    bandwidth = 2,
    adaptive = TRUE,
    neighbor_unit = "location",
    location_id = location_id
  )

  expect_equal(result$neighbor_location_id, c("A", "B"))
  expect_equal(result$neighbor_index, 1:4)
  expect_equal(result$distances, c(0, 0, 1, 1))
  expect_equal(result$local_bandwidth, 1)
  expect_equal(result$neighbor_unit, "location")
})


test_that("location neighborhoods require valid location identifiers", {
  coords <- matrix(
    c(
      0, 0,
      1, 0,
      2, 0
    ),
    ncol = 2,
    byrow = TRUE
  )

  expect_error(
    build_neighbors(
      coords = coords,
      focal_index = 1,
      bandwidth = 2,
      neighbor_unit = "location"
    ),
    "location_id is required"
  )

  expect_error(
    build_neighbors(
      coords = coords,
      focal_index = 1,
      bandwidth = 2,
      neighbor_unit = "location",
      location_id = c("A", "B")
    ),
    "same length"
  )

  expect_error(
    build_neighbors(
      coords = coords,
      focal_index = 1,
      bandwidth = 2,
      neighbor_unit = "location",
      location_id = c("A", NA, "C")
    ),
    "cannot contain NA"
  )
})

Try the gwrf package in your browser

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

gwrf documentation built on Aug. 24, 2026, 5:15 p.m.