| Title: | Population-Weighted Sampling of Geographic Locations in the United States |
|---|---|
| Description: | Generate geospatial locations within census block groups (BG; the smallest geographic unit for which population counts are available) within target counties, states, or across the entirety of the U.S. randomly selected according to population counts by using the Census Bureau reference data and optionally allow users to conduct temporal assignments on sampled locations using Covid-19 data. |
| Authors: | Rithy Techavoan Yean [aut, cre, cph], Andrew Holbrook [aut, cph], Jasen Zhang [ctb] |
| Maintainer: | Rithy Techavoan Yean <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.1 |
| Built: | 2026-10-14 08:12:29 UTC |
| Source: | https://github.com/techavoan/uspopulationsampler |
US_pop_sampler() using observed COVID-19 temporal distributions.This function assigns dates to sampled spatial points using observed county-level COVID-19 date distributions. It supports both in-memory datasets and large streamed Parquet datasets.
assign_dates_to_pts(pts, covid_data, output_dir = NULL, seed = NULL)assign_dates_to_pts(pts, covid_data, output_dir = NULL, seed = NULL)
pts |
One of:
Sampled points must contain at minimum:
|
covid_data |
A data.frame containing at minimum:
|
output_dir |
Optional directory where dated Parquet files
will be written when |
seed |
Optional integer seed for reproducible date assignment. |
Supported inputs include:
in-memory "synthetic_points" objects returned by
US_pop_sampler()
streamed "synthetic_points" objects containing a
path element
data.frames or data.tables containing sampled points
character paths to directories containing Parquet files
l Dates are assigned hierarchically:
observed dates within the matching county FIPS code
observed dates within the matching state
observed dates from the full COVID-19 dataset
Dates are sampled from the corresponding observed distribution. Sampling is performed without replacement when enough observed dates are available. Otherwise sampling is performed with replacement.
County-level dates are used whenever available. If no matching county dates exist, dates are drawn from the corresponding state, and finally from the complete COVID-19 dataset.
When pts is stored as Parquet files, data are processed one
file at a time and written directly to disk, allowing very large
synthetic datasets to be dated without loading all points into
memory simultaneously.
A "synthetic_points" object may represent either
an in-memory dataset or a streamed Parquet dataset.
If pts is supplied in memory, returns a
data.table containing the original sampled points
with an additional date column.
If pts refers to a Parquet directory, returns an object of
class "synthetic_points" containing:
Directory containing dated Parquet files
Number of Parquet files written
Character string describing the date assignment hierarchy.
data(df_bg_example) data(covid_data_example) # Generate synthetic points pts <- US_pop_sampler( N = 100, df = df_bg_example, seed = 123 ) # Assign dates using the example COVID-19 dataset pts <- assign_dates_to_pts( pts = pts, covid_data = covid_data_example, seed = 123 ) head(pts$date)data(df_bg_example) data(covid_data_example) # Generate synthetic points pts <- US_pop_sampler( N = 100, df = df_bg_example, seed = 123 ) # Assign dates using the example COVID-19 dataset pts <- assign_dates_to_pts( pts = pts, covid_data = covid_data_example, seed = 123 ) head(pts$date)
A small example dataset containing county-level COVID-19 observations for Delaware, Rhode Island, and Vermont during January 2022.This dataset is small to avoid having to load the entire COVID-19 data frame.
covid_data_examplecovid_data_example
A data frame containing:
Five-digit county FIPS code
Date of observation.
Name of County (stored as character)
Name of State (stored as character)
data(covid_data_example) head(covid_data_example)data(covid_data_example) head(covid_data_example)
A small subset of the 2020 Census block group population dataset used for examples and testing in USPopulationSampler.
df_bg_exampledf_bg_example
A data frame with rows representing Census block groups and columns including:
15-digit Census block group identifier.
Block Group Name With Number Identification
Two-digit state FIPS code.
Three-digit county FIPS code.
2020 Census population count for the block group.
2020 Census Tract Information
Block Group Number Identification
Simple feature geometry for the block group.
5 Digit FIPS Code
The dataset contains Census block groups from three states: Delaware, Rhode Island, and Vermont. Population counts are derived from the 2020 Decennial Census P1 table.
This dataset is intentionally small and is provided to demonstrate population-weighted sampling workflows without requiring download of the full national Census block group dataset.
U.S. Census Bureau 2020 Decennial Census.
data(df_bg_example) head(df_bg_example)data(df_bg_example) head(df_bg_example)
df_bg dataset containing
2020 Census block-group information, geometries, and population counts from Zenodo.The file is cached locally so repeated calls do not trigger
additional downloads unless overwrite = TRUE.
load_bg_data( destdir = tempdir(), filename = "US_Census_Blockgroup_Data_2020.rda", overwrite = FALSE )load_bg_data( destdir = tempdir(), filename = "US_Census_Blockgroup_Data_2020.rda", overwrite = FALSE )
destdir |
Directory used to store downloaded files.
Defaults to |
filename |
Name of the locally cached |
overwrite |
Logical; if |
The downloaded file is validated before loading:
File existence check
Detection of accidental HTML downloads
Verification that the object df_bg exists in the archive
Downloaded files are cached locally and reused in subsequent
calls unless overwrite = TRUE.
An sf object containing 2020 Census
block-group geometries, population counts, and identifying
geographic variables.
destdir <- tempfile() dir.create(destdir) bg_data <- load_bg_data(destdir = destdir) unlink(destdir, recursive = TRUE)destdir <- tempfile() dir.create(destdir) bg_data <- load_bg_data(destdir = destdir) unlink(destdir, recursive = TRUE)
assign_dates_to_pts().The file is cached locally so repeated calls do not trigger
additional downloads unless overwrite = TRUE.
load_covid_data( destdir = tempdir(), filename = "Covid_19_County_Case_Data.rda", overwrite = FALSE )load_covid_data( destdir = tempdir(), filename = "Covid_19_County_Case_Data.rda", overwrite = FALSE )
destdir |
Directory used to store downloaded files.
Defaults to |
filename |
Name of the locally cached |
overwrite |
Logical; if |
Downloaded files are validated before loading by checking
file existence, detection of accidental HTML downloads,
and verification that the object covid_cases exists
in the archive.
A data.frame containing county-level COVID-19 observations used for temporal assignment.
load_bg_data(), assign_dates_to_pts(), load_synthetic_covid()
destdir <- tempfile() dir.create(destdir) covid_data <- load_covid_data(destdir = destdir) unlink(destdir, recursive = TRUE)destdir <- tempfile() dir.create(destdir) covid_data <- load_covid_data(destdir = destdir) unlink(destdir, recursive = TRUE)
Files are cached locally so repeated calls do not trigger
additional downloads unless overwrite = TRUE.
load_synthetic_covid(dataset, destdir = tempdir(), overwrite = FALSE)load_synthetic_covid(dataset, destdir = tempdir(), overwrite = FALSE)
dataset |
Integer between 1 and 28 indicating which synthetic dataset to download. |
destdir |
Directory used to store downloaded files.
Defaults to |
overwrite |
Logical; if |
Synthetic datasets are hosted on Zenodo as compressed Parquet
files. Downloaded files are cached locally and reused in
subsequent calls unless overwrite = TRUE.
By default, downloaded files are stored in the temporary directory
returned by tempdir(). To retain downloaded files across
R sessions, users can provide a persistent directory through
destdir.
A data.frame containing the requested synthetic COVID-19 observations.
destdir <- tempfile() dir.create(destdir) sampled_dataset <- load_synthetic_covid( dataset = 1, destdir = destdir ) head(sampled_dataset) unlink(destdir, recursive = TRUE)destdir <- tempfile() dir.create(destdir) sampled_dataset <- load_synthetic_covid( dataset = 1, destdir = destdir ) head(sampled_dataset) unlink(destdir, recursive = TRUE)
Returns an Arrow Dataset object for lazy querying over partitioned Parquet files or returns an already materialized in-memory dataset.
open_synthetic_dataset(x)open_synthetic_dataset(x)
x |
One of:
|
When supplied with a directory or Arrow dataset reference,
the function returns an arrow::Dataset without loading
the data into memory. If an in-memory
"synthetic_points" object is supplied, it is returned
unchanged.
Use dplyr::collect() to materialize an
arrow::Dataset into memory.
Either:
an arrow::Dataset object for lazy querying, or
the supplied in-memory data.table if
x is already materialized.
if (requireNamespace("arrow", quietly = TRUE)) { tmp <- tempfile() arrow::write_dataset( data.frame( longitude = c(-118.2, -118.3), latitude = c(34.0, 34.1) ), path = tmp, format = "parquet" ) ds <- open_synthetic_dataset(tmp) ds }if (requireNamespace("arrow", quietly = TRUE)) { tmp <- tempfile() arrow::write_dataset( data.frame( longitude = c(-118.2, -118.3), latitude = c(34.0, 34.1) ), path = tmp, format = "parquet" ) ds <- open_synthetic_dataset(tmp) ds }
Locations are generated uniformly within census block-group polygons.
Sample counts are first allocated to block groups with probability proportional to population (optionally within user-defined state or county filters),
and points are then drawn independently within each polygon. Input rows with missing (NA), non-finite, or non-positive population
values are removed before sampling. Remaining rows are used as the sampling frame.
US_pop_sampler( N, df = NULL, state = NULL, fip_codes = NULL, parallel = FALSE, n_cores = NULL, seed = NULL, streaming = TRUE, stream_threshold = 1e+06, target_batch_points = NULL, output_dir = NULL )US_pop_sampler( N, df = NULL, state = NULL, fip_codes = NULL, parallel = FALSE, n_cores = NULL, seed = NULL, streaming = TRUE, stream_threshold = 1e+06, target_batch_points = NULL, output_dir = NULL )
N |
Integer scalar or named vector of target specifying number of synthetic points to generate. If a scalar, points are allocated across all eligible polygons proportional to population. If a named vector:
|
df |
An
If If |
state |
Optional character vector of state names or abbreviations. If provided, restricts sampling to block groups within the specified states; allocation is then performed within those subsets |
fip_codes |
Optional vector of county FIPS codes used (County Fip Codes 5 Digits)
to subset and allocate sampling. County filtering restricts the pool of eligible block groups rather than sampling counties directly. Cannot be used simultaneously with |
parallel |
Logical; if |
n_cores |
Integer number of cores to use when |
seed |
Optional integer seed for reproducible random sampling. |
streaming |
Logical; if |
stream_threshold |
Integer threshold above which streaming mode
is automatically enabled. Default is |
target_batch_points |
Approximate maximum number of points
processed in each sampling and write batch. If |
output_dir |
Directory where streamed Parquet files are written.
If |
Large sampling jobs can be streamed directly to Parquet files to avoid excessive memory use.
Population values are cleaned before sampling. Rows with missing, infinite, zero, or negative population values are excluded from the sampling frame. This allows users to supply Census-derived datasets containing uninhabited or incomplete geographies.
Streamed datasets can be reopened lazily using
open_synthetic_dataset() and materialized with
dplyr::collect() when needed.
If streaming is not triggered, returns a
data.table with class "synthetic_points" containing:
Longitude in WGS84 coordinates
Latitude in WGS84 coordinates
County FIPS code
Source polygon identifier
If streaming is triggered, returns a list with class
"synthetic_points" containing:
Directory containing Parquet files
Number of sampling batches written
Total number of generated points
data(df_bg_example) # Sample 100 synthetic points across Rhode Island pts <- US_pop_sampler( N = 100, df = df_bg_example, seed = 123 ) head(pts)data(df_bg_example) # Sample 100 synthetic points across Rhode Island pts <- US_pop_sampler( N = 100, df = df_bg_example, seed = 123 ) head(pts)