## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 6, fig.height = 4)

## ----data---------------------------------------------------------------------
library(GeoDensityR)
library(terra)

districts <- terra::vect(
  c("POLYGON((0 0, 2 0, 2 2, 0 2, 0 0))",
    "POLYGON((2 0, 4 0, 4 2, 2 2, 2 0))",
    "POLYGON((0 2, 4 2, 4 3, 0 3, 0 2))",
    "POLYGON((0 3, 4 3, 4 4, 0 4, 0 3))"),
  crs = "EPSG:4326"
)
districts$district_id <- c("D1", "D2", "D3", "D4")

census <- data.frame(
  ID         = c("D1", "D2", "D3", "D4"),
  population = c(120000, 45000, 300000, 80000)
)

## ----run----------------------------------------------------------------------
dens <- generate_density_raster(
  spatial_target  = districts,
  attribute_table = census,
  join_spatial    = "district_id",
  join_attribute  = "ID",
  value_col       = "population",
  resolution      = 0.1
)
dens

## ----plot---------------------------------------------------------------------
terra::plot(dens, main = "People per square kilometre")
terra::lines(districts)

## ----check--------------------------------------------------------------------
raster_total <- terra::global(dens * terra::cellSize(dens, unit = "km"), "sum", na.rm = TRUE)[[1]]
c(census_total = sum(census$population), raster_total = round(raster_total))

## ----real, eval = FALSE-------------------------------------------------------
# v   <- terra::project(terra::vect("India_State_Boundary.shp"), "EPSG:4326")
# tab <- read.csv("livestock_counts.csv")
# tab$Cattle <- as.numeric(gsub(",", "", tab$Cattle))
# 
# cattle <- generate_density_raster(
#   v, tab,
#   join_spatial   = "State_Name",
#   join_attribute = "State",
#   value_col      = "Cattle",
#   resolution     = 0.05,
#   output         = "cattle_density.tif"
# )

