docs: merge rendered roxygen markdown from GitHub pull request 6
Mirror to GitHub / mirror (push) Successful in 5s
R-CMD-check / check (push) Successful in 3m28s

Also regenerates man/cog_suggestions.Rd, which landed after that branch was
cut and still carried literal markdown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-04 17:18:29 -05:00
commit 5b1a59fc49
19 files changed
+708 -698

No files matched your search

+1
View File
@@ -37,6 +37,7 @@ Suggests:
ggplot2 ggplot2
Config/testthat/edition: 3 Config/testthat/edition: 3
VignetteBuilder: knitr VignetteBuilder: knitr
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.3.3 RoxygenNote: 7.3.3
MinCorpusSchema: 4 MinCorpusSchema: 4
MaxCorpusSchema: 7 MaxCorpusSchema: 7
+1 -1
View File
@@ -53,7 +53,7 @@
) )
} }
#' Per-subtype [min year, max year] extents for EVERY balance subtype in the #' Per-subtype \[min year, max year\] extents for EVERY balance subtype in the
#' mounted corpus, memoised for the session. #' mounted corpus, memoised for the session.
#' #'
#' The query carries no govid and no year predicate -- its answer is a property #' The query carries no govid and no year predicate -- its answer is a property
+70 -70
View File
@@ -21,109 +21,109 @@ cog_balances(
} }
\arguments{ \arguments{
\item{govid}{Canonical govid(s): a character vector, or a data frame with a \item{govid}{Canonical govid(s): a character vector, or a data frame with a
`canonical_govid` column (e.g. from [cog_gov_search()]). `NULL` to name \code{canonical_govid} column (e.g. from \code{\link[=cog_gov_search]{cog_gov_search()}}). \code{NULL} to name
the cohort by `state`/`type` instead.} the cohort by \code{state}/\code{type} instead.}
\item{years}{Integer vector of fiscal years.} \item{years}{Integer vector of fiscal years.}
\item{category}{Optional character vector of categories to keep. One of \item{category}{Optional character vector of categories to keep. One of
`"Fund Balances"`, `"Insurance Trust Balances"`, \code{"Fund Balances"}, \code{"Insurance Trust Balances"},
`"Retirement System Holdings"`. There is deliberately no `subtype` \code{"Retirement System Holdings"}. There is deliberately no \code{subtype}
argument: for holdings, `category` is a strict coarsening of argument: for holdings, \code{category} is a strict coarsening of
`balance_subtype` (unlike the money verbs, where the two axes cross), so \code{balance_subtype} (unlike the money verbs, where the two axes cross), so
every combination would be either redundant or empty. every combination would be either redundant or empty.
`category = "Fund Balances"` is exactly the `general` family \code{category = "Fund Balances"} is exactly the \code{general} family
(`W01`/`W31`/`W61`). `balance_subtype` is returned, so a finer split is (\code{W01}/\code{W31}/\code{W61}). \code{balance_subtype} is returned, so a finer split is
one `dplyr::filter()` away. The reserved pseudo-category one \code{dplyr::filter()} away. The reserved pseudo-category
`"All Categories"` (see [cog_spending()]) is **not** supported here and \code{"All Categories"} (see \code{\link[=cog_spending]{cog_spending()}}) is \strong{not} supported here and
errors with class `uscogdata_all_categories_unsupported`: it sums a errors with class \code{uscogdata_all_categories_unsupported}: it sums a
concept's subtype scope, and holdings are a stock with no concept concept's subtype scope, and holdings are a stock with no concept
vocabulary to sum across. Omit `category` to get every category broken vocabulary to sum across. Omit \code{category} to get every category broken
out instead.} out instead.}
\item{per_capita}{Divide holdings by population. Note this is a **stock per \item{per_capita}{Divide holdings by population. Note this is a \strong{stock per
resident** (reserves per person), which is *not* comparable to resident} (reserves per person), which is \emph{not} comparable to
[cog_spending()]'s per-capita figures -- those are a flow per person.} \code{\link[=cog_spending]{cog_spending()}}'s per-capita figures -- those are a flow per person.}
\item{adjust_to_year}{Deflate to this year's dollars (CPI-U).} \item{adjust_to_year}{Deflate to this year's dollars (CPI-U).}
\item{basis}{Accepted for uniformity with the money verbs, but currently a \item{basis}{Accepted for uniformity with the money verbs, but currently a
**no-op**: `harmonization_map` carries no balance-code rows, so harmonized \strong{no-op}: \code{harmonization_map} carries no balance-code rows, so harmonized
and raw space are identical for holdings. Reported in and raw space are identical for holdings. Reported in
`provenance$basis_note`.} \code{provenance$basis_note}.}
\item{recipe}{Optional harmonization recipe id (see [cog_recipes()]). \item{recipe}{Optional harmonization recipe id (see \code{\link[=cog_recipes]{cog_recipes()}}).
`"cash_securities_z77_wide"` and `"cash_securities_z78_wide"` bridge the \code{"cash_securities_z77_wide"} and \code{"cash_securities_z78_wide"} bridge the
wide era to the modern one.} wide era to the modern one.}
\item{state, type}{Name the cohort by predicate instead of by id: `state` is \item{state, type}{Name the cohort by predicate instead of by id: \code{state} is
a 2-letter USPS abbreviation (or a FIPS code) and `type` is one of a 2-letter USPS abbreviation (or a FIPS code) and \code{type} is one of
`"state"`, `"county"`, `"city"`, `"township"` (or the integer `0:3`) -- \code{"state"}, \code{"county"}, \code{"city"}, \code{"township"} (or the integer \code{0:3}) --
the same vocabulary, and the same internal coercion, as the same vocabulary, and the same internal coercion, as
[cog_gov_search()]. Both default to `NULL`. \code{\link[=cog_gov_search]{cog_gov_search()}}. Both default to \code{NULL}.
The cohort is then expressed as a subquery against `canonical_fips_xwalk` The cohort is then expressed as a subquery against \code{canonical_fips_xwalk}
inside each statement rather than round-tripped through R as a literal id inside each statement rather than round-tripped through R as a literal id
list. For a fleet-scale cohort that is the difference between a list. For a fleet-scale cohort that is the difference between a
301,591-character `IN` list re-parsed in 5--8 statements per call and a 301,591-character \code{IN} list re-parsed in 5--8 statements per call and a
constant-size predicate: measured at **94 ms versus 449 ms** for the same constant-size predicate: measured at \strong{94 ms versus 449 ms} for the same
FY2022 aggregate over the 20,106-government `type = "city"` cohort, within FY2022 aggregate over the 20,106-government \code{type = "city"} cohort, within
7% of the no-filter floor. 7\% of the no-filter floor.
Supplying `govid` **and** `state`/`type` INTERSECTS them -- the Supplying \code{govid} \strong{and} \code{state}/\code{type} INTERSECTS them -- the
governments in `govid` that also match the predicate -- rather than one governments in \code{govid} that also match the predicate -- rather than one
silently taking precedence. Naming no cohort at all (`govid`, `state` and silently taking precedence. Naming no cohort at all (\code{govid}, \code{state} and
`type` all `NULL`) aborts with class `uscogdata_no_cohort`. \code{type} all \code{NULL}) aborts with class \code{uscogdata_no_cohort}.
When the cohort is named by predicate, `provenance$scope$govids_found` When the cohort is named by predicate, \code{provenance$scope$govids_found}
and `govids_missing` are empty -- there is no id list to report against -- and \code{govids_missing} are empty -- there is no id list to report against --
and `provenance$scope$cohort` carries `state`, `type` and and \code{provenance$scope$cohort} carries \code{state}, \code{type} and
`n_governments` instead. A `govid`-named cohort reports exactly as before.} \code{n_governments} instead. A \code{govid}-named cohort reports exactly as before.}
\item{limit}{Maximum number of result rows to return, pushed into the SQL \item{limit}{Maximum number of result rows to return, pushed into the SQL
rather than applied after materializing every row. `NULL` (default) rather than applied after materializing every row. \code{NULL} (default)
returns everything. Cannot be combined with `recipe` -- see `offset` and returns everything. Cannot be combined with \code{recipe} -- see \code{offset} and
`total_rows`.} \code{total_rows}.}
\item{offset}{Rows to skip before `limit` starts counting (0-based). \item{offset}{Rows to skip before \code{limit} starts counting (0-based).
Ignored if `limit` is `NULL`; defaults to `0L` when `limit` is set.} Ignored if \code{limit} is \code{NULL}; defaults to \code{0L} when \code{limit} is set.}
\item{fiscal_period}{If `TRUE`, add `fiscal_year_end`, `period_start` and \item{fiscal_period}{If \code{TRUE}, add \code{fiscal_year_end}, \code{period_start} and
`period_end` to every row, as [cog_spending()] does. Holdings are a stock \code{period_end} to every row, as \code{\link[=cog_spending]{cog_spending()}} does. Holdings are a stock
measured at the end of the fiscal year, so `period_end` is the date the measured at the end of the fiscal year, so \code{period_end} is the date the
balance describes and `period_start` is the start of that fiscal year. balance describes and \code{period_start} is the start of that fiscal year.
Defaults to `FALSE`, which leaves the result unchanged.} Defaults to \code{FALSE}, which leaves the result unchanged.}
} }
\value{ \value{
Tibble with columns `year`, `canonical_govid`, `gov_name`, Tibble with columns \code{year}, \code{canonical_govid}, \code{gov_name},
`balance_subtype`, `category`, `amt_nominal`, `codes_included`, \code{balance_subtype}, \code{category}, \code{amt_nominal}, \code{codes_included},
`aggregate_fallback`, plus optional `amt_per_capita_nominal` and \code{aggregate_fallback}, plus optional \code{amt_per_capita_nominal} and
`pop_source` (when `per_capita = TRUE`), optional `amt_real` (when \code{pop_source} (when \code{per_capita = TRUE}), optional \code{amt_real} (when
`adjust_to_year` is set), and optional `amt_per_capita_real` (only when \code{adjust_to_year} is set), and optional \code{amt_per_capita_real} (only when
**both** `per_capita = TRUE` and `adjust_to_year` are set -- there is no \strong{both} \code{per_capita = TRUE} and \code{adjust_to_year} are set -- there is no
nominal per-capita column to deflate otherwise), and `fiscal_year_end`, nominal per-capita column to deflate otherwise), and \code{fiscal_year_end},
`period_start` and `period_end` when `fiscal_period = TRUE`. Amounts are \code{period_start} and \code{period_end} when \code{fiscal_period = TRUE}. Amounts are
full US dollars. full US dollars.
Carries a `provenance` attribute matching Carries a \code{provenance} attribute matching
`inst/schemas/provenance-v1.json`, whose `balance_caveats` block reports \code{inst/schemas/provenance-v1.json}, whose \code{balance_caveats} block reports
`not_gaap`, `not_gaap_note`, `coverage_window` (measured year extents for \code{not_gaap}, \code{not_gaap_note}, \code{coverage_window} (measured year extents for
every balance subtype in the mounted corpus, not only the observed ones) every balance subtype in the mounted corpus, not only the observed ones)
and `truncated` (the observed subtypes whose coverage falls short of the and \code{truncated} (the observed subtypes whose coverage falls short of the
requested years). `expenditure_concept`/`revenue_concept` are `NA` -- requested years). \code{expenditure_concept}/\code{revenue_concept} are \code{NA} --
holdings are a stock, not a flow, so neither concept vocabulary applies. holdings are a stock, not a flow, so neither concept vocabulary applies.
When `limit` is set, also carries a `total_rows` attribute: the full When \code{limit} is set, also carries a \code{total_rows} attribute: the full
unpaginated row count, computed by the same query (`COUNT(*) OVER()`) unpaginated row count, computed by the same query (\verb{COUNT(*) OVER()})
rather than a second scan. rather than a second scan.
} }
\description{ \description{
Returns Census cash-and-security holdings (`category_type = "balance"`): Returns Census cash-and-security holdings (\code{category_type = "balance"}):
fund balances, retirement system holdings and insurance trust balances. fund balances, retirement system holdings and insurance trust balances.
} }
\section{Holdings are not GAAP fund balance}{ \section{Holdings are not GAAP fund balance}{
Census holdings are **gross** -- no liabilities are netted -- so a reserve Census holdings are \strong{gross} -- no liabilities are netted -- so a reserve
ratio built from them overstates what is actually available. They are not ratio built from them overstates what is actually available. They are not
comparable to a GAAP fund balance from an ACFR. comparable to a GAAP fund balance from an ACFR.
} }
+7 -7
View File
@@ -7,21 +7,21 @@
cog_basket_resolution(x, expand_candidates = FALSE) cog_basket_resolution(x, expand_candidates = FALSE)
} }
\arguments{ \arguments{
\item{x}{A tibble returned by basket-mode [cog_gov_search()].} \item{x}{A tibble returned by basket-mode \code{\link[=cog_gov_search]{cog_gov_search()}}.}
\item{expand_candidates}{Logical. If `TRUE`, keeps the `candidates` \item{expand_candidates}{Logical. If \code{TRUE}, keeps the \code{candidates}
list-column (full-schema match candidates per input row). Default list-column (full-schema match candidates per input row). Default
`FALSE`.} \code{FALSE}.}
} }
\value{ \value{
A tibble with the resolution audit trail. A tibble with the resolution audit trail.
} }
\description{ \description{
Returns the resolution tibble attached to a basket-mode result of Returns the resolution tibble attached to a basket-mode result of
[cog_gov_search()]. One row per input entry; `status` is one of \code{\link[=cog_gov_search]{cog_gov_search()}}. One row per input entry; \code{status} is one of
`"resolved"`, `"largest_pop"`, `"ambiguous"`, `"no_match"`. By default \code{"resolved"}, \code{"largest_pop"}, \code{"ambiguous"}, \code{"no_match"}. By default
the `candidates` list-column is dropped for readable printing; pass the \code{candidates} list-column is dropped for readable printing; pass
`expand_candidates = TRUE` to keep it. \code{expand_candidates = TRUE} to keep it.
} }
\examples{ \examples{
\dontrun{ \dontrun{
+5 -5
View File
@@ -7,15 +7,15 @@
cog_basket_unresolved(x) cog_basket_unresolved(x)
} }
\arguments{ \arguments{
\item{x}{A tibble returned by basket-mode [cog_gov_search()].} \item{x}{A tibble returned by basket-mode \code{\link[=cog_gov_search]{cog_gov_search()}}.}
} }
\value{ \value{
A tibble (subset of [cog_basket_resolution()]). A tibble (subset of \code{\link[=cog_basket_resolution]{cog_basket_resolution()}}).
} }
\description{ \description{
Convenience wrapper that returns just the rows where `status` is Convenience wrapper that returns just the rows where \code{status} is
`"ambiguous"` or `"no_match"` — the ones the user likely wants to \code{"ambiguous"} or \code{"no_match"} — the ones the user likely wants to
refine before piping into a query verb. The `candidates` list-column refine before piping into a query verb. The \code{candidates} list-column
is preserved so the user can drill into ambiguous match sets. is preserved so the user can drill into ambiguous match sets.
} }
\examples{ \examples{
+18 -18
View File
@@ -7,33 +7,33 @@
cog_categories(type = NULL, pattern = NULL) cog_categories(type = NULL, pattern = NULL)
} }
\arguments{ \arguments{
\item{type}{Either `NULL` (default, every row: expenditure, revenue and \item{type}{Either \code{NULL} (default, every row: expenditure, revenue and
balance), `"spending"`, `"revenue"`, or `"balance"`.} balance), \code{"spending"}, \code{"revenue"}, or \code{"balance"}.}
\item{pattern}{Optional regex matched case-insensitively against the \item{pattern}{Optional regex matched case-insensitively against the
`category` column (e.g. `"Police"` or `"Tax"`).} \code{category} column (e.g. \code{"Police"} or \code{"Tax"}).}
} }
\value{ \value{
Tibble with columns `category`, `category_type`, `subtype`, Tibble with columns \code{category}, \code{category_type}, \code{subtype},
`n_codes`, `item_codes` (comma-separated, alphabetical). Sorted by \code{n_codes}, \code{item_codes} (comma-separated, alphabetical). Sorted by
`category_type`, `category`, `subtype`. Includes one row per flow for the \code{category_type}, \code{category}, \code{subtype}. Includes one row per flow for the
reserved pseudo-category `"All Categories"`, which carries `NA` for reserved pseudo-category \code{"All Categories"}, which carries \code{NA} for
`subtype`, `n_codes` and `item_codes` because it is a query mode rather \code{subtype}, \code{n_codes} and \code{item_codes} because it is a query mode rather
than a crosswalk entry — see [cog_spending()]'s `category` argument. than a crosswalk entry — see \code{\link[=cog_spending]{cog_spending()}}'s \code{category} argument.
} }
\description{ \description{
Returns the category taxonomy exposed by the corpus's Returns the category taxonomy exposed by the corpus's
`summary_categories` view, grouped to one row per \code{summary_categories} view, grouped to one row per
`(category, subtype)` pair. Use this to discover valid `category` \verb{(category, subtype)} pair. Use this to discover valid \code{category}
values for [cog_spending()] / [cog_revenue()] / [cog_balances()] / values for \code{\link[=cog_spending]{cog_spending()}} / \code{\link[=cog_revenue]{cog_revenue()}} / \code{\link[=cog_balances]{cog_balances()}} /
[cog_geographic_rollup()] and to audit which Census item codes feed \code{\link[=cog_geographic_rollup]{cog_geographic_rollup()}} and to audit which Census item codes feed
each category. each category.
} }
\details{ \details{
`subtype` COALESCEs the crosswalk's three subtype columns, so it carries \code{subtype} COALESCEs the crosswalk's three subtype columns, so it carries
`spend_subtype` on expenditure rows, `revenue_subtype` on revenue rows and \code{spend_subtype} on expenditure rows, \code{revenue_subtype} on revenue rows and
`balance_subtype` on balance rows. Note that [cog_balances()] itself takes \code{balance_subtype} on balance rows. Note that \code{\link[=cog_balances]{cog_balances()}} itself takes
no `subtype` argument — for holdings, `category` is a strict coarsening of no \code{subtype} argument — for holdings, \code{category} is a strict coarsening of
`balance_subtype` — but the value is surfaced here because it is the \code{balance_subtype} — but the value is surfaced here because it is the
discovery surface downstream consumers build their vocabulary from. discovery surface downstream consumers build their vocabulary from.
} }
+22 -21
View File
@@ -7,18 +7,18 @@
cog_explain(result, format = c("print", "list")) cog_explain(result, format = c("print", "list"))
} }
\arguments{ \arguments{
\item{result}{A tibble returned by a `cog_*` verb.} \item{result}{A tibble returned by a \verb{cog_*} verb.}
\item{format}{`"print"` (default) for a human-readable cli summary; \item{format}{\code{"print"} (default) for a human-readable cli summary;
returns `result` invisibly for chaining. `"list"` returns the raw returns \code{result} invisibly for chaining. \code{"list"} returns the raw
provenance list (identical to `attr(result, "provenance")`).} provenance list (identical to \code{attr(result, "provenance")}).}
} }
\value{ \value{
Either `result` (invisibly) or the provenance list. Either \code{result} (invisibly) or the provenance list.
} }
\description{ \description{
Prints the structured provenance attached to a tibble returned by any Prints the structured provenance attached to a tibble returned by any
`cog_*` verb, or returns it as a list for downstream use (MCP tools, \verb{cog_*} verb, or returns it as a list for downstream use (MCP tools,
dashboards, JSON export). dashboards, JSON export).
} }
\section{Two kinds of series break}{ \section{Two kinds of series break}{
@@ -26,28 +26,29 @@ dashboards, JSON export).
Catalogued breaks reach you without being asked for, in two disjoint Catalogued breaks reach you without being asked for, in two disjoint
fields, because a caveat about one series and a caveat about the whole fields, because a caveat about one series and a caveat about the whole
corpus are different claims: corpus are different claims:
\itemize{
\item \strong{\code{series_break_refs}} — breaks matched against the item codes actually
present in this result. A break in one code you queried.
\item \strong{\code{corpus_break_refs}} — breaks catalogued with \code{fin_code = "ALL"},
which are statements about the corpus rather than about any one code:
dollar precision across the 1976/1977 boundary (\code{SB085}), imputation
exclusion from FY2002 (\code{SB087}), the FY2012 dense-to-sparse
representation change (\code{SB194}), and the FY2017 government-identifier
change (\code{SB086}). These are selected on the break-year window alone.
}
* **`series_break_refs`** — breaks matched against the item codes actually \code{SB194} is the one most likely to matter: a query spanning FY2011 to FY2012
present in this result. A break in one code you queried.
* **`corpus_break_refs`** — breaks catalogued with `fin_code = "ALL"`,
which are statements about the corpus rather than about any one code:
dollar precision across the 1976/1977 boundary (`SB085`), imputation
exclusion from FY2002 (`SB087`), the FY2012 dense-to-sparse
representation change (`SB194`), and the FY2017 government-identifier
change (`SB086`). These are selected on the break-year window alone.
`SB194` is the one most likely to matter: a query spanning FY2011 to FY2012
crosses the boundary where an absent cell stops meaning "Census published crosses the boundary where an absent cell stops meaning "Census published
$0" and starts meaning "not reported". $0" and starts meaning "not reported".
} }
\section{Other provenance blocks}{ \section{Other provenance blocks}{
`transformations$units_conversion` records the `$1,000s`-to-dollars \code{transformations$units_conversion} records the \verb{$1,000s}-to-dollars
multiply that every amount column has already had applied. multiply that every amount column has already had applied.
`transformations$per_capita` records the population denominator and its \code{transformations$per_capita} records the population denominator and its
year range. `coverage` and `coverage_mode` appear on multi-government year range. \code{coverage} and \code{coverage_mode} appear on multi-government
results (see [cog_geographic_rollup()]). `completion` appears when results (see \code{\link[=cog_geographic_rollup]{cog_geographic_rollup()}}). \code{completion} appears when
`complete = TRUE`. `balance_caveats` appears on [cog_balances()] results. \code{complete = TRUE}. \code{balance_caveats} appears on \code{\link[=cog_balances]{cog_balances()}} results.
} }
+19 -19
View File
@@ -16,41 +16,41 @@ cog_find_peers(
) )
} }
\arguments{ \arguments{
\item{target_govid}{Character scalar — `canonical_govid` of the target.} \item{target_govid}{Character scalar — \code{canonical_govid} of the target.}
\item{year}{Integer scalar. Cohort vintage. When `NULL` (default), uses the \item{year}{Integer scalar. Cohort vintage. When \code{NULL} (default), uses the
most recent year for which the target has an observed population in most recent year for which the target has an observed population in
`gov_population_yearly`.} \code{gov_population_yearly}.}
\item{same_type}{If `TRUE` (default) restrict peers to the target's \item{same_type}{If \code{TRUE} (default) restrict peers to the target's
`govs_type`.} \code{govs_type}.}
\item{same_state}{If `TRUE` restrict peers to the target's `fips_state`. \item{same_state}{If \code{TRUE} restrict peers to the target's \code{fips_state}.
Default `FALSE`.} Default \code{FALSE}.}
\item{pop_range}{Length-2 numeric vector giving lower/upper bounds.} \item{pop_range}{Length-2 numeric vector giving lower/upper bounds.}
\item{is_ratio}{If `TRUE` (default) `pop_range` is multiplied by the \item{is_ratio}{If \code{TRUE} (default) \code{pop_range} is multiplied by the
target's population at `year` to produce absolute bounds. If `FALSE`, target's population at \code{year} to produce absolute bounds. If \code{FALSE},
`pop_range` is interpreted as absolute population counts.} \code{pop_range} is interpreted as absolute population counts.}
\item{max_peers}{Integer cap on the number of peers returned.} \item{max_peers}{Integer cap on the number of peers returned.}
\item{coverage}{Survey-cycle handling; see [cog_peer_compare()]. Here it \item{coverage}{Survey-cycle handling; see \code{\link[=cog_peer_compare]{cog_peer_compare()}}. Here it
governs the cohort VINTAGE when `year` is `NULL`: `"census"` snaps to the governs the cohort VINTAGE when \code{year} is \code{NULL}: \code{"census"} snaps to the
most recent census year with an observed population, so a cohort is not most recent census year with an observed population, so a cohort is not
built from a sample year in which most of the candidate universe is built from a sample year in which most of the candidate universe is
absent. `"consistent"` needs a year range, which cohort selection does not absent. \code{"consistent"} needs a year range, which cohort selection does not
have, so it selects like `"all"` and is carried on the result as have, so it selects like \code{"all"} and is carried on the result as
`attr(x, "coverage")` for [cog_peer_compare()].} \code{attr(x, "coverage")} for \code{\link[=cog_peer_compare]{cog_peer_compare()}}.}
} }
\value{ \value{
Tibble with columns `canonical_govid`, `gov_name`, `fips_state`, Tibble with columns \code{canonical_govid}, \code{gov_name}, \code{fips_state},
`population`, `pop_ratio`, `rank`. The cohort year is attached as \code{population}, \code{pop_ratio}, \code{rank}. The cohort year is attached as
`attr(x, "cohort_year")`. \code{attr(x, "cohort_year")}.
} }
\description{ \description{
Selects peer governments by combinations of government type, state, and Selects peer governments by combinations of government type, state, and
population range at a chosen `year`. Peers are ordered by `|log(pop_ratio)|` population range at a chosen \code{year}. Peers are ordered by \verb{|log(pop_ratio)|}
ascending (closest to the target's population first). ascending (closest to the target's population first).
} }
+22 -21
View File
@@ -7,19 +7,19 @@
cog_fiscal_periods(govid, years) cog_fiscal_periods(govid, years)
} }
\arguments{ \arguments{
\item{govid}{Character vector of `canonical_govid` values, or a data frame \item{govid}{Character vector of \code{canonical_govid} values, or a data frame
with a `canonical_govid` column.} with a \code{canonical_govid} column.}
\item{years}{Integer vector of survey years.} \item{years}{Integer vector of survey years.}
} }
\value{ \value{
Tibble with one row per requested government and year, in the Tibble with one row per requested government and year, in the
order `govid` x `years`: `canonical_govid`, `year`, `fiscal_year_end` order \code{govid} x \code{years}: \code{canonical_govid}, \code{year}, \code{fiscal_year_end}
(integer MMDD), `period_start` and `period_end` (Dates, inclusive). (integer MMDD), \code{period_start} and \code{period_end} (Dates, inclusive).
} }
\description{ \description{
Returns the calendar months each survey year covers for each government. Returns the calendar months each survey year covers for each government.
The corpus's `year` is the Census survey year, and a survey year covers The corpus's \code{year} is the Census survey year, and a survey year covers
different months for different governments. different months for different governments.
} }
\section{The survey-year rule}{ \section{The survey-year rule}{
@@ -27,17 +27,18 @@ different months for different governments.
Census assigns each government's fiscal year to a survey year by when the Census assigns each government's fiscal year to a survey year by when the
fiscal year ended. Survey year Y holds the fiscal year that ended between fiscal year ended. Survey year Y holds the fiscal year that ended between
July 1 of Y-1 and June 30 of Y. The corpus records each government-year's July 1 of Y-1 and June 30 of Y. The corpus records each government-year's
fiscal year end as `fiscal_year_end`, an MMDD integer such as `630` or fiscal year end as \code{fiscal_year_end}, an MMDD integer such as \code{630} or
`1231`. \code{1231}.
Survey year 2017 therefore covers, for a county, city or township: Survey year 2017 therefore covers, for a county, city or township:
\itemize{
* `fiscal_year_end = 630` (June 30): the fiscal year ending June 30, \item \code{fiscal_year_end = 630} (June 30): the fiscal year ending June 30,
2017, so July 2016 to June 2017. 2017, so July 2016 to June 2017.
* `930` (September 30): the fiscal year ending September 30, 2016, so \item \code{930} (September 30): the fiscal year ending September 30, 2016, so
October 2015 to September 2016. October 2015 to September 2016.
* `1231` (December 31): the fiscal year ending December 31, 2016, so \item \code{1231} (December 31): the fiscal year ending December 31, 2016, so
January to December 2016. January to December 2016.
}
A city with a December year end and a city with a June year end are both A city with a December year end and a city with a June year end are both
"2017" in the corpus, but their figures are six months apart. A September "2017" in the corpus, but their figures are six months apart. A September
@@ -57,11 +58,11 @@ rests on the documentation alone. For New York (March 31) and the 46 states
with a June 30 year end, the two rules give the same months. with a June 30 year end, the two rules give the same months.
A government can change its fiscal year end, so the periods are looked up A government can change its fiscal year end, so the periods are looked up
per government-year. Where the corpus has no `fiscal_year_end` for a per government-year. Where the corpus has no \code{fiscal_year_end} for a
government-year, or the government has no rows that year, the period is government-year, or the government has no rows that year, the period is
`NA`. Most of FY1993 is `NA`: 99% of its government-years have no usable \code{NA}. Most of FY1993 is \code{NA}: 99\% of its government-years have no usable
value in the public corpus as of November 2026. So do 5% to 11% in FY1978 value in the public corpus as of November 2026. So do 5\% to 11\% in FY1978
and FY1987 to FY1990, and under 3% in every other year. and FY1987 to FY1990, and under 3\% in every other year.
From FY2023 the source files mark some rows as estimates carried forward From FY2023 the source files mark some rows as estimates carried forward
from an earlier year. The periods here describe the survey year, not the from an earlier year. The periods here describe the survey year, not the
@@ -78,7 +79,7 @@ cog_fiscal_periods(
} }
} }
\seealso{ \seealso{
[cog_survey_year()] for the reverse mapping; the `fiscal_period` \code{\link[=cog_survey_year]{cog_survey_year()}} for the reverse mapping; the \code{fiscal_period}
argument of [cog_spending()], [cog_revenue()] and [cog_balances()] to get argument of \code{\link[=cog_spending]{cog_spending()}}, \code{\link[=cog_revenue]{cog_revenue()}} and \code{\link[=cog_balances]{cog_balances()}} to get
the same columns on every row. the same columns on every row.
} }
+66 -64
View File
@@ -16,102 +16,104 @@ cog_geographic_rollup(
} }
\arguments{ \arguments{
\item{govids}{Named list with any non-empty subset of elements named \item{govids}{Named list with any non-empty subset of elements named
`state`, `county`, `city`. Each element is a character vector of \code{state}, \code{county}, \code{city}. Each element is a character vector of
`canonical_govid` values. At least one layer required.} \code{canonical_govid} values. At least one layer required.}
\item{category}{Single category name or character vector (passed through \item{category}{Single category name or character vector (passed through
to [cog_spending()]), or the reserved `"All Categories"` for one summed to \code{\link[=cog_spending]{cog_spending()}}), or the reserved \code{"All Categories"} for one summed
row per `(year, canonical_govid, subtype)` covering every category in the row per \verb{(year, canonical_govid, subtype)} covering every category in the
concept's scope. `"All Categories"` is the efficient way to build a concept's scope. \code{"All Categories"} is the efficient way to build a
geographic total: without it a caller must issue one rollup per category geographic total: without it a caller must issue one rollup per category
and sum the results themselves.} and sum the results themselves.}
\item{years}{Integer vector of years.} \item{years}{Integer vector of years.}
\item{per_capita}{If `TRUE`, per-capita uses each gov's own per-year \item{per_capita}{If \code{TRUE}, per-capita uses each gov's own per-year
population from `gov_population_yearly`. Govs with missing population population from \code{gov_population_yearly}. Govs with missing population
are excluded from the result.} are excluded from the result.}
\item{adjust_to_year}{Integer base year for CPI-U conversion, or `NULL`.} \item{adjust_to_year}{Integer base year for CPI-U conversion, or \code{NULL}.}
\item{expenditure_concept}{`"primary"` (default), `"direct"`, or \item{expenditure_concept}{\code{"primary"} (default), \code{"direct"}, or
`"total"` -- see [cog_spending()] for the three concepts. `"total"` is \code{"total"} -- see \code{\link[=cog_spending]{cog_spending()}} for the three concepts. \code{"total"} is
refused here because combining Total across multiple layers of refused here because combining Total across multiple layers of
government double-counts intergovernmental transfers (a state's payment government double-counts intergovernmental transfers (a state's payment
to a school district is the same dollar the district reports as its own to a school district is the same dollar the district reports as its own
Direct spending); `"primary"` and `"direct"` combine safely.} Direct spending); \code{"primary"} and \code{"direct"} combine safely.}
\item{coverage}{How to handle the Census of Governments survey cycle, \item{coverage}{How to handle the Census of Governments survey cycle,
which is a **complete census only in years ending in 2 and 7** -- every which is a \strong{complete census only in years ending in 2 and 7} -- every
other year is a sample, and the sample varies enormously (on the bundled other year is a sample, and the sample varies enormously (on the bundled
fixture, Wisconsin's 608-city universe reports 597 governments in FY2012 fixture, Wisconsin's 608-city universe reports 597 governments in FY2012
and 112 in FY2019). and 112 in FY2019).
\itemize{
\item \code{"all"} (default) -- every unit that reported that year. Unchanged
behaviour, so existing code keeps working.
\item \code{"census"} -- census years only. Aborts if the requested range holds
none, rather than silently returning nothing.
\item \code{"consistent"} -- only units reporting in \emph{every} requested year, giving
a balanced panel.
}
* `"all"` (default) -- every unit that reported that year. Unchanged Regardless of mode, \code{provenance$coverage} always carries per-year
behaviour, so existing code keeps working. \code{n_units_expected}, \code{n_units_collected}, \code{n_units_reporting} and
* `"census"` -- census years only. Aborts if the requested range holds \code{is_census_year}, and \code{provenance$coverage_mode} records the mode.
none, rather than silently returning nothing. \code{is_census_year} is a statement about the \strong{survey calendar}, never a
* `"consistent"` -- only units reporting in *every* requested year, giving claim of completeness: FY1967 is a census year in which only 97 of
a balanced panel. Wisconsin's 608 cities report. \code{n_units_reporting} is
category-conditional and is not a response rate on its own -- see
Regardless of mode, `provenance$coverage` always carries per-year "Reading \code{coverage}" below for what each counter answers.}
`n_units_expected`, `n_units_collected`, `n_units_reporting` and
`is_census_year`, and `provenance$coverage_mode` records the mode.
`is_census_year` is a statement about the **survey calendar**, never a
claim of completeness: FY1967 is a census year in which only 97 of
Wisconsin's 608 cities report. `n_units_reporting` is
category-conditional and is not a response rate on its own -- see
"Reading `coverage`" below for what each counter answers.}
} }
\value{ \value{
Tibble with columns `year`, `layer`, `canonical_govid`, `gov_name`, Tibble with columns \code{year}, \code{layer}, \code{canonical_govid}, \code{gov_name},
`spend_subtype`, `category`, `amt_nominal`, optional `amt_real` / \code{spend_subtype}, \code{category}, \code{amt_nominal}, optional \code{amt_real} /
`amt_per_capita_nominal` / `amt_per_capita_real`, optional `pop_source`, \code{amt_per_capita_nominal} / \code{amt_per_capita_real}, optional \code{pop_source},
`codes_included`, `aggregate_fallback`, `scope_note`, `notes`. Carries a \code{codes_included}, \code{aggregate_fallback}, \code{scope_note}, \code{notes}. Carries a
`provenance` attribute with `verb = "cog_geographic_rollup"`, `layers`, \code{provenance} attribute with \code{verb = "cog_geographic_rollup"}, \code{layers},
and `rollup$included_govids` / `rollup$excluded_govids`. and \code{rollup$included_govids} / \code{rollup$excluded_govids}.
} }
\description{ \description{
Wraps [cog_spending()], tags each row with its layer, and attaches a Wraps \code{\link[=cog_spending]{cog_spending()}}, tags each row with its layer, and attaches a
human-readable `scope_note` documenting geographic-scope caveats (e.g. human-readable \code{scope_note} documenting geographic-scope caveats (e.g.
"county totals include areas outside the listed city"). Useful for "county totals include areas outside the listed city"). Useful for
"place portraits" that compare a city to the surrounding county and "place portraits" that compare a city to the surrounding county and
containing state on one set of axes. containing state on one set of axes.
} }
\details{ \details{
When `per_capita = TRUE`, rows whose government has no observed When \code{per_capita = TRUE}, rows whose government has no observed
population in that year (`pop_source == "unavailable"`) are dropped from population in that year (\code{pop_source == "unavailable"}) are dropped from
the result. The dropped govids are recorded in the result. The dropped govids are recorded in
`provenance$rollup$excluded_govids`. This excludes special districts \code{provenance$rollup$excluded_govids}. This excludes special districts
(gov type 4) and school districts (gov type 5) from per-capita rollups (gov type 4) and school districts (gov type 5) from per-capita rollups
by design — see `vignette('population-denominators')`. by design — see \code{vignette('population-denominators')}.
} }
\section{Reading `coverage`}{ \section{Reading \code{coverage}}{
`provenance$coverage` carries three per-year counters: \code{provenance$coverage} carries three per-year counters:
\itemize{
\item \code{n_units_expected} -- how many governments you asked about.
\item \code{n_units_collected} -- how many of those appear in the corpus at all
that year (in ANY category), separating governments Census did not
collect from governments it did.
\item \code{n_units_reporting} -- how many have rows for the SPECIFIC category you
requested. This is always <= n_units_collected. A collected government
can have no "Police" rows and still pay for policing: the rows leave out
intergovernmental expenditure, so a city that pays the county sheriff
and reports the payment as intergovernmental (code \code{M62}) has none. Of
34 cities with documented sheriff contracts, nine of 102 city-years
(FY2012, FY2017 and FY2022; corpus build of 2026-10-26) looked like
this, and the other 93 reported direct Police spending.
}
* `n_units_expected` -- how many governments you asked about. \strong{\code{n_units_reporting} is category-conditional} and therefore \strong{not a
* `n_units_collected` -- how many of those appear in the corpus at all response rate}: \code{n_units_reporting / n_units_expected} conflates sampling
that year (in ANY category), separating governments Census did not
collect from governments it did.
* `n_units_reporting` -- how many have rows for the SPECIFIC category you
requested. This is always <= n_units_collected. A collected government
can have no "Police" rows and still pay for policing: the rows leave out
intergovernmental expenditure, so a city that pays the county sheriff
and reports the payment as intergovernmental (code `M62`) has none. Of
34 cities with documented sheriff contracts, nine of 102 city-years
(FY2012, FY2017 and FY2022; corpus build of 2026-10-26) looked like
this, and the other 93 reported direct Police spending.
**`n_units_reporting` is category-conditional** and therefore **not a
response rate**: `n_units_reporting / n_units_expected` conflates sampling
(never collected) with collected governments that have no rows in your (never collected) with collected governments that have no rows in your
category. Use `n_units_collected / n_units_expected` for the true category. Use \code{n_units_collected / n_units_expected} for the true
collection rate, and `n_units_reporting / n_units_collected` for category collection rate, and \code{n_units_reporting / n_units_collected} for category
participation among collected units. participation among collected units.
In FY2022, a census year, 393 of Georgia's 567 cities report In FY2022, a census year, 393 of Georgia's 567 cities report
`category = "Police"`. Of the other 174, 32 were not collected and 142 were \code{category = "Police"}. Of the other 174, 32 were not collected and 142 were
collected with no Police rows. A city that contracts with the county sheriff collected with no Police rows. A city that contracts with the county sheriff
lands in the second group only when it reports no direct Police spending, for lands in the second group only when it reports no direct Police spending, for
example when it files the payment as intergovernmental expenditure; the example when it files the payment as intergovernmental expenditure; the
@@ -120,7 +122,7 @@ counters do not say how many of the 142 do.
A census year and a sample year collect different sets of governments, so A census year and a sample year collect different sets of governments, so
participation across the two mixes a change in which governments were participation across the two mixes a change in which governments were
collected with any change in spending. Compare census years with each other, collected with any change in spending. Compare census years with each other,
or the same governments across years. `is_census_year` marks which is which, or the same governments across years. \code{is_census_year} marks which is which,
and `vignette("coverage-counters")` has worked examples. and \code{vignette("coverage-counters")} has worked examples.
} }
+49 -46
View File
@@ -16,69 +16,72 @@ cog_gov_search(
\item{name}{Character vector of place name(s). Length 1 = utility mode; \item{name}{Character vector of place name(s). Length 1 = utility mode;
length >1 = basket mode.} length >1 = basket mode.}
\item{state}{2-letter USPS abbreviation (e.g. `"FL"`), FIPS integer \item{state}{2-letter USPS abbreviation (e.g. \code{"FL"}), FIPS integer
(e.g. `12`), or `NULL`. In basket mode, length 1 recycles across (e.g. \code{12}), or \code{NULL}. In basket mode, length 1 recycles across
all entries; otherwise must match `length(name)`.} all entries; otherwise must match \code{length(name)}.}
\item{type}{Government type: integer in `0:3` or one of `"state"`, \item{type}{Government type: integer in \code{0:3} or one of \code{"state"},
`"county"`, `"city"`, `"township"`, or `NA`/`NULL`. Per-row optional \code{"county"}, \code{"city"}, \code{"township"}, or \code{NA}/\code{NULL}. Per-row optional
in basket mode (recycles from length 1). Excluded types `4`/`5` (or in basket mode (recycles from length 1). Excluded types \code{4}/\code{5} (or
`"special_district"` / `"school_district"`) trigger an explanatory \code{"special_district"} / \code{"school_district"}) trigger an explanatory
message and an empty result.} message and an empty result.}
\item{limit}{Maximum number of rows to return, applied in SQL. `NULL` \item{limit}{Maximum number of rows to return, applied in SQL. \code{NULL}
(default) returns every match -- which, with no other filter, is the (default) returns every match -- which, with no other filter, is the
entire crosswalk. Utility mode only: pagination has no meaning in basket entire crosswalk. Utility mode only: pagination has no meaning in basket
mode, where the result is one resolved row per requested name in input mode, where the result is one resolved row per requested name in input
order, and is refused there with class order, and is refused there with class
`uscogdata_basket_pagination_conflict`.} \code{uscogdata_basket_pagination_conflict}.}
\item{offset}{Rows to skip before `limit` starts counting (0-based). \item{offset}{Rows to skip before \code{limit} starts counting (0-based).
Ignored if `limit` is `NULL`; defaults to `0L` when `limit` is set.} Ignored if \code{limit} is \code{NULL}; defaults to \code{0L} when \code{limit} is set.}
} }
\value{ \value{
A tibble of `canonical_fips_xwalk` rows. In utility mode, all A tibble of \code{canonical_fips_xwalk} rows. In utility mode, all
matches sorted by `population_acs` desc, ties broken by matches sorted by \code{population_acs} desc, ties broken by
`canonical_govid`. In basket mode, resolved rows in input order, with \code{canonical_govid}. In basket mode, resolved rows in input order, with
`attr(., "resolution")` set to the sidecar tibble. \code{attr(., "resolution")} set to the sidecar tibble.
When `limit` is set, carries a `total_rows` attribute: the full When \code{limit} is set, carries a \code{total_rows} attribute: the full
unpaginated match count, computed by the same query (`COUNT(*) OVER()`) unpaginated match count, computed by the same query (\verb{COUNT(*) OVER()})
rather than a second scan. rather than a second scan.
} }
\description{ \description{
Resolves human-readable place names into rows of `canonical_fips_xwalk`, Resolves human-readable place names into rows of \code{canonical_fips_xwalk},
the cross-vintage canonical-government registry. Operates in two modes: the cross-vintage canonical-government registry. Operates in two modes:
} }
\details{ \details{
* **Utility mode** (single `name`, the original behavior): returns all \itemize{
rows whose `gov_name` contains `name` as a **literal, case-insensitive \item \strong{Utility mode} (single \code{name}, the original behavior): returns all
substring**, sorted by `population_acs` descending. Useful for rows whose \code{gov_name} contains \code{name} as a \strong{literal, case-insensitive
exploratory lookups. Regex metacharacters in `name` are escaped, so a substring}, sorted by \code{population_acs} descending. Useful for
government is findable by its own complete name even when that name exploratory lookups. Regex metacharacters in \code{name} are escaped, so a
contains parentheses or a period. government is findable by its own complete name even when that name
* **Basket mode** (`length(name) > 1`): resolves each input row to a contains parentheses or a period.
single canonical govid and returns a tibble in input order, suitable \item \strong{Basket mode} (\code{length(name) > 1}): resolves each input row to a
for piping straight into [cog_spending()] / [cog_revenue()] / single canonical govid and returns a tibble in input order, suitable
[cog_geographic_rollup()]. Carries an audit sidecar accessible via for piping straight into \code{\link[=cog_spending]{cog_spending()}} / \code{\link[=cog_revenue]{cog_revenue()}} /
[cog_basket_resolution()] / [cog_basket_unresolved()]. \code{\link[=cog_geographic_rollup]{cog_geographic_rollup()}}. Carries an audit sidecar accessible via
\code{\link[=cog_basket_resolution]{cog_basket_resolution()}} / \code{\link[=cog_basket_unresolved]{cog_basket_unresolved()}}.
}
\strong{Basket-mode resolution algorithm} (per input row):
**Basket-mode resolution algorithm** (per input row): \enumerate{
1. Filter `canonical_fips_xwalk` by `state` and (if non-NA) `type`. \item Filter \code{canonical_fips_xwalk} by \code{state} and (if non-NA) \code{type}.
2. **Exact pass:** case-insensitive equality against `gov_name`. \item \strong{Exact pass:} case-insensitive equality against \code{gov_name}.
Single hit -> resolved. Multiple -> step 4. Single hit -> resolved. Multiple -> step 4.
3. **Substring fallback:** case-insensitive literal substring against \item \strong{Substring fallback:} case-insensitive literal substring against
`gov_name` (metacharacters escaped). \code{gov_name} (metacharacters escaped).
Single hit -> resolved (`match_method = "substring"`). Zero hits -> Single hit -> resolved (\code{match_method = "substring"}). Zero hits ->
`status = "no_match"`. Multiple hits -> step 4. \code{status = "no_match"}. Multiple hits -> step 4.
4. **Disambiguation:** if matches share one `govs_type`, pick the \item \strong{Disambiguation:} if matches share one \code{govs_type}, pick the
largest-population row (`status = "largest_pop"`). If they span >=2 largest-population row (\code{status = "largest_pop"}). If they span >=2
types, no row is added (`status = "ambiguous"`); the user should types, no row is added (\code{status = "ambiguous"}); the user should
re-run with `type` specified. re-run with \code{type} specified.
}
Resolved rows form the returned tibble in input order. Unresolved Resolved rows form the returned tibble in input order. Unresolved
inputs (`ambiguous` / `no_match`) appear only in the sidecar. inputs (\code{ambiguous} / \code{no_match}) appear only in the sidecar.
} }
\examples{ \examples{
\dontrun{ \dontrun{
@@ -113,6 +116,6 @@ refined <- cog_gov_search(
} }
} }
\seealso{ \seealso{
[cog_basket_resolution()], [cog_basket_unresolved()], \code{\link[=cog_basket_resolution]{cog_basket_resolution()}}, \code{\link[=cog_basket_unresolved]{cog_basket_unresolved()}},
[cog_spending()], [cog_revenue()]. \code{\link[=cog_spending]{cog_spending()}}, \code{\link[=cog_revenue]{cog_revenue()}}.
} }
+4 -4
View File
@@ -7,12 +7,12 @@
cog_manifest() cog_manifest()
} }
\value{ \value{
Named list: `schema_version`, `built_at`, `pipeline_commit`, Named list: \code{schema_version}, \code{built_at}, \code{pipeline_commit},
`data_vintage`, `scope`, `years` (schema v5+), `schema`, `files`. \code{data_vintage}, \code{scope}, \code{years} (schema v5+), \code{schema}, \code{files}.
} }
\description{ \description{
Opens a session (connecting to the configured corpus) if none is active, Opens a session (connecting to the configured corpus) if none is active,
then returns the manifest exactly as parsed from `manifest.json`. Useful then returns the manifest exactly as parsed from \code{manifest.json}. Useful
for consumers that need the published year range (`years` block, schema for consumers that need the published year range (\code{years} block, schema
v5+) or the partition list without issuing a data query. v5+) or the partition list without issuing a data query.
} }
+8 -8
View File
@@ -14,22 +14,22 @@ cog_mirror(
\arguments{ \arguments{
\item{dest}{Destination directory. Created if missing.} \item{dest}{Destination directory. Created if missing.}
\item{include}{Subset of `c("long", "metadata", "docs")` controlling \item{include}{Subset of \code{c("long", "metadata", "docs")} controlling
which manifest sections to mirror.} which manifest sections to mirror.}
\item{overwrite}{If `TRUE`, re-copy even when the local SHA matches.} \item{overwrite}{If \code{TRUE}, re-copy even when the local SHA matches.}
\item{progress}{If `TRUE`, show a cli progress bar.} \item{progress}{If \code{TRUE}, show a cli progress bar.}
} }
\value{ \value{
Invisibly, a tibble of `(path, sha256, size_bytes, status)` Invisibly, a tibble of \verb{(path, sha256, size_bytes, status)}
rows where `status` is `"downloaded"` or `"cached"`. rows where \code{status} is \code{"downloaded"} or \code{"cached"}.
} }
\description{ \description{
Downloads (or copies, for local-path fixture URLs) every file listed in Downloads (or copies, for local-path fixture URLs) every file listed in
the session's `manifest.json` into `dest`, preserving the relative path the session's \code{manifest.json} into \code{dest}, preserving the relative path
structure. Files already present with a matching SHA-256 hash are structure. Files already present with a matching SHA-256 hash are
skipped unless `overwrite = TRUE`. The resulting directory can be skipped unless \code{overwrite = TRUE}. The resulting directory can be
pointed at via `options(uscogdata.url = paste0(dest, "/"))` for offline pointed at via \code{options(uscogdata.url = paste0(dest, "/"))} for offline
analysis. analysis.
} }
+89 -89
View File
@@ -18,123 +18,123 @@ cog_peer_compare(
\arguments{ \arguments{
\item{target_govid}{Character scalar.} \item{target_govid}{Character scalar.}
\item{peers}{A tibble from [cog_find_peers()] or a character vector of \item{peers}{A tibble from \code{\link[=cog_find_peers]{cog_find_peers()}} or a character vector of
`canonical_govid`s.} \code{canonical_govid}s.}
\item{category}{Character scalar or vector.} \item{category}{Character scalar or vector.}
\item{years}{Integer vector.} \item{years}{Integer vector.}
\item{per_capita}{Default `TRUE` — peer compare usually normalizes by \item{per_capita}{Default \code{TRUE} — peer compare usually normalizes by
population.} population.}
\item{adjust_to_year}{Integer base year for CPI-U conversion or `NULL`.} \item{adjust_to_year}{Integer base year for CPI-U conversion or \code{NULL}.}
\item{expenditure_concept}{`"primary"` (default), `"direct"`, or \item{expenditure_concept}{\code{"primary"} (default), \code{"direct"}, or
`"total"` -- see [cog_spending()] for the three concepts. `"total"` is \code{"total"} -- see \code{\link[=cog_spending]{cog_spending()}} for the three concepts. \code{"total"} is
refused here because combining Total across peer sets counts refused here because combining Total across peer sets counts
intergovernmental transfers twice; `"primary"` and `"direct"` combine intergovernmental transfers twice; \code{"primary"} and \code{"direct"} combine
safely.} safely.}
\item{coverage}{How to handle the Census of Governments survey cycle, \item{coverage}{How to handle the Census of Governments survey cycle,
which is a **complete census only in years ending in 2 and 7** -- every which is a \strong{complete census only in years ending in 2 and 7} -- every
other year is a sample, and the sample varies enormously (on the bundled other year is a sample, and the sample varies enormously (on the bundled
fixture, Wisconsin's 608-city universe reports 597 governments in FY2012 fixture, Wisconsin's 608-city universe reports 597 governments in FY2012
and 112 in FY2019). and 112 in FY2019).
\itemize{
\item \code{"all"} (default) -- every unit that reported that year. Unchanged
behaviour, so existing code keeps working.
\item \code{"census"} -- census years only. Aborts if the requested range holds
none, rather than silently returning nothing.
\item \code{"consistent"} -- only units reporting in \emph{every} requested year, giving
a balanced panel.
}
* `"all"` (default) -- every unit that reported that year. Unchanged Regardless of mode, \code{provenance$coverage} always carries per-year
behaviour, so existing code keeps working. \code{n_units_expected}, \code{n_units_collected}, \code{n_units_reporting} and
* `"census"` -- census years only. Aborts if the requested range holds \code{is_census_year}, and \code{provenance$coverage_mode} records the mode.
none, rather than silently returning nothing. \code{is_census_year} is a statement about the \strong{survey calendar}, never a
* `"consistent"` -- only units reporting in *every* requested year, giving claim of completeness: FY1967 is a census year in which only 97 of
a balanced panel. Wisconsin's 608 cities report. \code{n_units_reporting} is
category-conditional and is not a response rate on its own -- see
"Reading \code{coverage}" below for what each counter answers.
Regardless of mode, `provenance$coverage` always carries per-year The comparison target is exempt from \code{"consistent"} balancing -- it is the
`n_units_expected`, `n_units_collected`, `n_units_reporting` and subject of the comparison, not a member of the cohort -- and the
`is_census_year`, and `provenance$coverage_mode` records the mode. \verb{summary_*} quantiles are computed AFTER the filter, so they describe the
`is_census_year` is a statement about the **survey calendar**, never a cohort actually returned. \code{n_units_reporting} counts peers only, against
claim of completeness: FY1967 is a census year in which only 97 of the cohort size: "3 of your 15 peers reported in FY2019".}
Wisconsin's 608 cities report. `n_units_reporting` is
category-conditional and is not a response rate on its own -- see
"Reading `coverage`" below for what each counter answers.
The comparison target is exempt from `"consistent"` balancing -- it is the
subject of the comparison, not a member of the cohort -- and the
`summary_*` quantiles are computed AFTER the filter, so they describe the
cohort actually returned. `n_units_reporting` counts peers only, against
the cohort size: "3 of your 15 peers reported in FY2019".}
} }
\value{ \value{
Tibble matching [cog_spending()]'s columns, plus a `role` Tibble matching \code{\link[=cog_spending]{cog_spending()}}'s columns, plus a \code{role}
column taking values `"target"`, `"peer"`, `"summary_p25"`, column taking values \code{"target"}, \code{"peer"}, \code{"summary_p25"},
`"summary_p50"`, or `"summary_p75"`, `target_rank` (target's rank \code{"summary_p50"}, or \code{"summary_p75"}, \code{target_rank} (target's rank
among target+peers at `max(years)`, NA for other rows), and among target+peers at \code{max(years)}, NA for other rows), and
`cohort_year` (the year used to build the peer cohort, read from \code{cohort_year} (the year used to build the peer cohort, read from
`attr(peers, "cohort_year")`; `NA` when `peers` was a bare character \code{attr(peers, "cohort_year")}; \code{NA} when \code{peers} was a bare character
vector). Provenance reports `verb = "cog_peer_compare"`, `peer_count`, vector). Provenance reports \code{verb = "cog_peer_compare"}, \code{peer_count},
`cohort_year`, and `cohort_govids`. \code{cohort_year}, and \code{cohort_govids}.
**The `summary_*` rows are per-category quantiles: they are not additive.** \strong{The \verb{summary_*} rows are per-category quantiles: they are not additive.}
Each one is computed **within each `(year, spend_subtype, Each one is computed \strong{within each \verb{(year, spend_subtype, category)} cell} across the peer set, so a \code{summary_p50} row is \emph{the
category)` cell** across the peer set, so a `summary_p50` row is *the median peer's value in that one category}, not \emph{the value of the median
median peer's value in that one category*, not *the value of the median peer's total}. The median peer for Police and the median peer for Fire
peer's total*. The median peer for Police and the median peer for Fire are usually different governments, so summing \verb{summary_*} rows across
are usually different governments, so summing `summary_*` rows across categories does not give any peer's total and misstates the band it
categories does not give any peer's total and misstates the band it appears to describe — measured at −32.7\% to +251.0\% across 24 years on
appears to describe — measured at −32.7% to +251.0% across 24 years on one cohort, with a sign flip at FY2012.
one cohort, with a sign flip at FY2012.
Facet by `role` **and** `category` (the documented use, and what the Facet by \code{role} \strong{and} \code{category} (the documented use, and what the
rows are built for). For a genuine "median peer's total spending" line, rows are built for). For a genuine "median peer's total spending" line,
sum each peer's own categories first and take the quantile of those sum each peer's own categories first and take the quantile of those
per-government totals: per-government totals:
```r \if{html}{\out{<div class="sourceCode r">}}\preformatted{library(dplyr)
library(dplyr) cmp |>
cmp |> filter(role \%in\% c("target", "peer")) |>
filter(role %in% c("target", "peer")) |> group_by(year, role, canonical_govid) |>
group_by(year, role, canonical_govid) |> summarise(total = sum(amt_per_capita_real, na.rm = TRUE), .groups = "drop") |>
summarise(total = sum(amt_per_capita_real, na.rm = TRUE), .groups = "drop") |> filter(role == "peer") |>
filter(role == "peer") |> group_by(year) |>
group_by(year) |> summarise(p50 = quantile(total, 0.5, na.rm = TRUE))
summarise(p50 = quantile(total, 0.5, na.rm = TRUE)) }\if{html}{\out{</div>}}
```
} }
\description{ \description{
Pulls spending for the target plus a peer set (either a Pulls spending for the target plus a peer set (either a
[cog_find_peers()] result or a character vector of `canonical_govid`) and \code{\link[=cog_find_peers]{cog_find_peers()}} result or a character vector of \code{canonical_govid}) and
appends peer-distribution summary rows (`summary_p25`, `summary_p50`, appends peer-distribution summary rows (\code{summary_p25}, \code{summary_p50},
`summary_p75`) so the result can be faceted by `role` in a single ggplot \code{summary_p75}) so the result can be faceted by \code{role} in a single ggplot
call. Those summary rows are quantiles **within each category**, not call. Those summary rows are quantiles \strong{within each category}, not
quantiles of each peer's total — see the `@return` section before summing quantiles of each peer's total — see the \verb{@return} section before summing
them. them.
} }
\section{Reading `coverage`}{ \section{Reading \code{coverage}}{
`provenance$coverage` carries three per-year counters: \code{provenance$coverage} carries three per-year counters:
\itemize{
\item \code{n_units_expected} -- how many governments you asked about.
\item \code{n_units_collected} -- how many of those appear in the corpus at all
that year (in ANY category), separating governments Census did not
collect from governments it did.
\item \code{n_units_reporting} -- how many have rows for the SPECIFIC category you
requested. This is always <= n_units_collected. A collected government
can have no "Police" rows and still pay for policing: the rows leave out
intergovernmental expenditure, so a city that pays the county sheriff
and reports the payment as intergovernmental (code \code{M62}) has none. Of
34 cities with documented sheriff contracts, nine of 102 city-years
(FY2012, FY2017 and FY2022; corpus build of 2026-10-26) looked like
this, and the other 93 reported direct Police spending.
}
* `n_units_expected` -- how many governments you asked about. \strong{\code{n_units_reporting} is category-conditional} and therefore \strong{not a
* `n_units_collected` -- how many of those appear in the corpus at all response rate}: \code{n_units_reporting / n_units_expected} conflates sampling
that year (in ANY category), separating governments Census did not
collect from governments it did.
* `n_units_reporting` -- how many have rows for the SPECIFIC category you
requested. This is always <= n_units_collected. A collected government
can have no "Police" rows and still pay for policing: the rows leave out
intergovernmental expenditure, so a city that pays the county sheriff
and reports the payment as intergovernmental (code `M62`) has none. Of
34 cities with documented sheriff contracts, nine of 102 city-years
(FY2012, FY2017 and FY2022; corpus build of 2026-10-26) looked like
this, and the other 93 reported direct Police spending.
**`n_units_reporting` is category-conditional** and therefore **not a
response rate**: `n_units_reporting / n_units_expected` conflates sampling
(never collected) with collected governments that have no rows in your (never collected) with collected governments that have no rows in your
category. Use `n_units_collected / n_units_expected` for the true category. Use \code{n_units_collected / n_units_expected} for the true
collection rate, and `n_units_reporting / n_units_collected` for category collection rate, and \code{n_units_reporting / n_units_collected} for category
participation among collected units. participation among collected units.
In FY2022, a census year, 393 of Georgia's 567 cities report In FY2022, a census year, 393 of Georgia's 567 cities report
`category = "Police"`. Of the other 174, 32 were not collected and 142 were \code{category = "Police"}. Of the other 174, 32 were not collected and 142 were
collected with no Police rows. A city that contracts with the county sheriff collected with no Police rows. A city that contracts with the county sheriff
lands in the second group only when it reports no direct Police spending, for lands in the second group only when it reports no direct Police spending, for
example when it files the payment as intergovernmental expenditure; the example when it files the payment as intergovernmental expenditure; the
@@ -143,7 +143,7 @@ counters do not say how many of the 142 do.
A census year and a sample year collect different sets of governments, so A census year and a sample year collect different sets of governments, so
participation across the two mixes a change in which governments were participation across the two mixes a change in which governments were
collected with any change in spending. Compare census years with each other, collected with any change in spending. Compare census years with each other,
or the same governments across years. `is_census_year` marks which is which, or the same governments across years. \code{is_census_year} marks which is which,
and `vignette("coverage-counters")` has worked examples. and \code{vignette("coverage-counters")} has worked examples.
} }
+7 -7
View File
@@ -8,15 +8,15 @@ cog_recipes(pattern = NULL)
} }
\arguments{ \arguments{
\item{pattern}{Optional regex matched case-insensitively against \item{pattern}{Optional regex matched case-insensitively against
`recipe_id` or `label`.} \code{recipe_id} or \code{label}.}
} }
\value{ \value{
Tibble with columns `recipe_id`, `label`, `n_components`, Tibble with columns \code{recipe_id}, \code{label}, \code{n_components},
`year_min`, `year_max` (the min/max component year coverage), sorted by \code{year_min}, \code{year_max} (the min/max component year coverage), sorted by
`recipe_id`. \code{recipe_id}.
} }
\description{ \description{
Recipes are multi-code cross-vintage series (see [cog_spending()]'s Recipes are multi-code cross-vintage series (see \code{\link[=cog_spending]{cog_spending()}}'s
`recipe` argument) catalogued in the corpus's `harmonization_recipes` \code{recipe} argument) catalogued in the corpus's \code{harmonization_recipes}
table. Use this to discover valid `recipe` ids. table. Use this to discover valid \code{recipe} ids.
} }
+114 -114
View File
@@ -22,163 +22,163 @@ cog_revenue(
) )
} }
\arguments{ \arguments{
\item{govid}{Character vector of `canonical_govid` values, or `NULL` to name \item{govid}{Character vector of \code{canonical_govid} values, or \code{NULL} to name
the cohort by `state`/`type` instead. One of `govid`, `state`, or `type` the cohort by \code{state}/\code{type} instead. One of \code{govid}, \code{state}, or \code{type}
is required.} is required.}
\item{years}{Integer vector of years.} \item{years}{Integer vector of years.}
\item{category}{Character vector of category names (from \item{category}{Character vector of category names (from
`summary_categories.category`), or `NULL` for all categories broken out \code{summary_categories.category}), or \code{NULL} for all categories broken out
one row each. The reserved value `"All Categories"` instead returns a one row each. The reserved value \code{"All Categories"} instead returns a
single summed row per `(year, canonical_govid, subtype)`, covering every single summed row per \verb{(year, canonical_govid, subtype)}, covering every
category inside the requested concept's subtype scope. It cannot be category inside the requested concept's subtype scope. It cannot be
combined with other category names, and it is not the same thing as combined with other category names, and it is not the same thing as
`revenue_concept = "total"`: the concept chooses which subtypes are in \code{revenue_concept = "total"}: the concept chooses which subtypes are in
scope, `"All Categories"` chooses whether rows inside that scope are scope, \code{"All Categories"} chooses whether rows inside that scope are
broken out or summed. Because the result keeps one row per broken out or summed. Because the result keeps one row per
`revenue_subtype`, filtering the returned frame to \code{revenue_subtype}, filtering the returned frame to
`revenue_subtype == "own_source"` gives an own-source revenue total.} \code{revenue_subtype == "own_source"} gives an own-source revenue total.}
\item{per_capita}{If `TRUE`, adds `amt_per_capita_nominal` (and \item{per_capita}{If \code{TRUE}, adds \code{amt_per_capita_nominal} (and
`amt_per_capita_real` when `adjust_to_year` is set) using the per-year \code{amt_per_capita_real} when \code{adjust_to_year} is set) using the per-year
Census F-33 population from `gov_population_yearly`. Result also gains Census F-33 population from \code{gov_population_yearly}. Result also gains
a `pop_source` column with values `"census_f33"` or `"unavailable"` a \code{pop_source} column with values \code{"census_f33"} or \code{"unavailable"}
(the latter for gov types 4/5 and any row whose population is missing (the latter for gov types 4/5 and any row whose population is missing
in that year).} in that year).}
\item{adjust_to_year}{Integer base year for CPI-U real-dollar conversion, \item{adjust_to_year}{Integer base year for CPI-U real-dollar conversion,
or `NULL` for nominal only.} or \code{NULL} for nominal only.}
\item{basis}{`"harmonized"` (default) sums item codes through the \item{basis}{\code{"harmonized"} (default) sums item codes through the
cross-vintage harmonization mapping (folding series-break-affected cross-vintage harmonization mapping (folding series-break-affected
codes onto a comparable target and excluding aggregate / discontinued codes onto a comparable target and excluding aggregate / discontinued
rows -- see the `harmonization` block in `cog_explain()`); `"raw"` rows -- see the \code{harmonization} block in \code{cog_explain()}); \code{"raw"}
reproduces the pre-Phase-R2 behavior (published item codes, no reproduces the pre-Phase-R2 behavior (published item codes, no
folding). On a corpus with `schema_version < 5` (no harmonization folding). On a corpus with \code{schema_version < 5} (no harmonization
tables), `basis` silently resolves to `"raw"` when left at its default tables), \code{basis} silently resolves to \code{"raw"} when left at its default
and the resolution is recorded in the provenance; explicitly passing and the resolution is recorded in the provenance; explicitly passing
`basis = "harmonized"` on such a corpus aborts. Ignored when `recipe` \code{basis = "harmonized"} on such a corpus aborts. Ignored when \code{recipe}
is set (see below).} is set (see below).}
\item{recipe}{Optional harmonization recipe id (see [cog_recipes()]) for \item{recipe}{Optional harmonization recipe id (see \code{\link[=cog_recipes]{cog_recipes()}}) for
multi-code cross-vintage series that a 1:1 harmonized_code mapping multi-code cross-vintage series that a 1:1 harmonized_code mapping
can't express (e.g. a wide-era aggregate that only splits into leaf can't express (e.g. a wide-era aggregate that only splits into leaf
codes in the modern era). Mutually exclusive with `category`. The codes in the modern era). Mutually exclusive with \code{category}. The
result's subtype column reads `"recipe"` and `category` reads the result's subtype column reads \code{"recipe"} and \code{category} reads the
recipe's label. Requires `schema_version >= 5`. A recipe query bypasses recipe's label. Requires \code{schema_version >= 5}. A recipe query bypasses
`basis` entirely (it joins `long` directly rather than going through \code{basis} entirely (it joins \code{long} directly rather than going through
the `*_annotated`/`*_annotated_harmonized` views), so the `basis` the \verb{*_annotated}/\verb{*_annotated_harmonized} views), so the \code{basis}
argument is ignored and the result's provenance reports argument is ignored and the result's provenance reports
`basis = "recipe"` with an inert `harmonization` block (`applied = \code{basis = "recipe"} with an inert \code{harmonization} block (\code{applied = FALSE}, pointing at the \code{recipe} block instead) rather than a
FALSE`, pointing at the `recipe` block instead) rather than a possibly-misleading \code{"harmonized"}/\code{"raw"} value.}
possibly-misleading `"harmonized"`/`"raw"` value.}
\item{revenue_concept}{Which of Census's two published revenue concepts to \item{revenue_concept}{Which of Census's two published revenue concepts to
return. Concepts are defined as sets of the crosswalk's `revenue_subtype` return. Concepts are defined as sets of the crosswalk's \code{revenue_subtype}
values -- never as item-code first letters, which cannot classify values -- never as item-code first letters, which cannot classify
correctly (prefix `Y` spans revenue, expenditure and balance codes, and correctly (prefix \code{Y} spans revenue, expenditure and balance codes, and
prefix `X` does the same): prefix \code{X} does the same):
\itemize{
\item \code{"general"} (default) -- Census General Revenue: \code{own_source} +
\code{federal} + \code{state} + \code{local_aid}. The manual defines this concept by
subtraction (section 4.3: \emph{"General revenue comprises all revenue
except that classified as liquor store, utility, or insurance trust
revenue"}), so utility (\code{A91}-\code{A94}), liquor store (\code{A90}) and
insurance trust revenue are all excluded.
\item \code{"total"} -- Census Total Revenue: every revenue subtype, i.e.
\code{general} plus utility, liquor store, and insurance trust revenue
(\code{Y01}/\code{Y02}/\code{Y04}/\code{Y11}/\code{Y12}/\code{Y51}/\code{Y52} and the employee-retirement
\code{X01}/\code{X02}/\code{X05}/\code{X08}).
}
* `"general"` (default) -- Census General Revenue: `own_source` + The two are related by Census's own identity, \verb{Total Revenue = General + Utility + Liquor Store + Insurance Trust}.
`federal` + `state` + `local_aid`. The manual defines this concept by
subtraction (section 4.3: *"General revenue comprises all revenue
except that classified as liquor store, utility, or insurance trust
revenue"*), so utility (`A91`-`A94`), liquor store (`A90`) and
insurance trust revenue are all excluded.
* `"total"` -- Census Total Revenue: every revenue subtype, i.e.
`general` plus utility, liquor store, and insurance trust revenue
(`Y01`/`Y02`/`Y04`/`Y11`/`Y12`/`Y51`/`Y52` and the employee-retirement
`X01`/`X02`/`X05`/`X08`).
The two are related by Census's own identity, `Total Revenue = General + Note that the employee-retirement (\code{X}) codes stop at FY2016, when those
Utility + Liquor Store + Insurance Trust`. systems moved out of the annual finance file into the separate Annual
Survey of Public Pensions, so a \code{"total"} series steps down at the
FY2016/FY2017 seam for reasons that are about collection scope rather
than revenue (series breaks \code{SB197}-\code{SB202}).}
Note that the employee-retirement (`X`) codes stop at FY2016, when those \item{complete}{If \code{TRUE}, fill the requested grid so that a cell the
systems moved out of the annual finance file into the separate Annual corpus does not carry still appears, labelled with \strong{why} it is
Survey of Public Pensions, so a `"total"` series steps down at the missing, and add a \code{value_source} column to every row:
FY2016/FY2017 seam for reasons that are about collection scope rather \itemize{
than revenue (series breaks `SB197`-`SB202`).} \item \code{"reported"} — the corpus carries this cell.
\item \code{"census_zero"} — dense-source year (\verb{<= FY2011}), cell absent:
Census published \verb{$0}. \code{amt_nominal} is \code{0}.
\item \code{"not_reported"} — sparse-source year (\verb{>= FY2012}), cell absent: the
government did not report, and the value is unknown. \code{amt_nominal} is
\code{NA}, \strong{not} \code{0} — writing a zero there would invent data.
}
\item{complete}{If `TRUE`, fill the requested grid so that a cell the The grid comes from the corpus's \code{code_set} table, scoped to each
corpus does not carry still appears, labelled with **why** it is government's own type, so a county is never filled with cells only a
missing, and add a `value_source` column to every row: state can report. Reported rows are passed through untouched.
* `"reported"` — the corpus carries this cell. Defaults to \code{FALSE} (the historical behaviour: absent cells simply do
* `"census_zero"` — dense-source year (`<= FY2011`), cell absent: not appear). Needs a corpus published from 2026-07-29 onward, which is
Census published `$0`. `amt_nominal` is `0`. when \code{representation}/\code{code_set} began shipping; aborts with class
* `"not_reported"` — sparse-source year (`>= FY2012`), cell absent: the \code{uscogdata_representation_unavailable} otherwise. Not available with
government did not report, and the value is unknown. `amt_nominal` is \code{recipe} or with \code{expenditure_concept = "total"} (class
`NA`, **not** `0` — writing a zero there would invent data. \code{uscogdata_complete_unsupported}) — neither draws its cells from
\code{code_set}.}
The grid comes from the corpus's `code_set` table, scoped to each
government's own type, so a county is never filled with cells only a
state can report. Reported rows are passed through untouched.
Defaults to `FALSE` (the historical behaviour: absent cells simply do
not appear). Needs a corpus published from 2026-07-29 onward, which is
when `representation`/`code_set` began shipping; aborts with class
`uscogdata_representation_unavailable` otherwise. Not available with
`recipe` or with `expenditure_concept = "total"` (class
`uscogdata_complete_unsupported`) — neither draws its cells from
`code_set`.}
\item{limit}{Maximum number of result rows to return, pushed into the SQL \item{limit}{Maximum number of result rows to return, pushed into the SQL
query itself (`LIMIT`/`OFFSET`) rather than applied after the full query itself (\code{LIMIT}/\code{OFFSET}) rather than applied after the full
result is materialized. `NULL` (the default) returns every matching row, result is materialized. \code{NULL} (the default) returns every matching row,
exactly as before this parameter existed. Mutually exclusive with exactly as before this parameter existed. Mutually exclusive with
`recipe` and with `complete = TRUE` -- see `offset` and `total_rows`.} \code{recipe} and with \code{complete = TRUE} -- see \code{offset} and \code{total_rows}.}
\item{offset}{Rows to skip before `limit` starts counting (0-based). \item{offset}{Rows to skip before \code{limit} starts counting (0-based).
Ignored if `limit` is `NULL`; defaults to `0L` when `limit` is set.} Ignored if \code{limit} is \code{NULL}; defaults to \code{0L} when \code{limit} is set.}
\item{state, type}{Name the cohort by predicate instead of by id: `state` is \item{state, type}{Name the cohort by predicate instead of by id: \code{state} is
a 2-letter USPS abbreviation (or a FIPS code) and `type` is one of a 2-letter USPS abbreviation (or a FIPS code) and \code{type} is one of
`"state"`, `"county"`, `"city"`, `"township"` (or the integer `0:3`) -- \code{"state"}, \code{"county"}, \code{"city"}, \code{"township"} (or the integer \code{0:3}) --
the same vocabulary, and the same internal coercion, as the same vocabulary, and the same internal coercion, as
[cog_gov_search()]. Both default to `NULL`. \code{\link[=cog_gov_search]{cog_gov_search()}}. Both default to \code{NULL}.
The cohort is then expressed as a subquery against `canonical_fips_xwalk` The cohort is then expressed as a subquery against \code{canonical_fips_xwalk}
inside each statement rather than round-tripped through R as a literal id inside each statement rather than round-tripped through R as a literal id
list. For a fleet-scale cohort that is the difference between a list. For a fleet-scale cohort that is the difference between a
301,591-character `IN` list re-parsed in 5--8 statements per call and a 301,591-character \code{IN} list re-parsed in 5--8 statements per call and a
constant-size predicate: measured at **94 ms versus 449 ms** for the same constant-size predicate: measured at \strong{94 ms versus 449 ms} for the same
FY2022 aggregate over the 20,106-government `type = "city"` cohort, within FY2022 aggregate over the 20,106-government \code{type = "city"} cohort, within
7% of the no-filter floor. 7\% of the no-filter floor.
Supplying `govid` **and** `state`/`type` INTERSECTS them -- the Supplying \code{govid} \strong{and} \code{state}/\code{type} INTERSECTS them -- the
governments in `govid` that also match the predicate -- rather than one governments in \code{govid} that also match the predicate -- rather than one
silently taking precedence. Naming no cohort at all (`govid`, `state` and silently taking precedence. Naming no cohort at all (\code{govid}, \code{state} and
`type` all `NULL`) aborts with class `uscogdata_no_cohort`. \code{type} all \code{NULL}) aborts with class \code{uscogdata_no_cohort}.
When the cohort is named by predicate, `provenance$scope$govids_found` When the cohort is named by predicate, \code{provenance$scope$govids_found}
and `govids_missing` are empty -- there is no id list to report against -- and \code{govids_missing} are empty -- there is no id list to report against --
and `provenance$scope$cohort` carries `state`, `type` and and \code{provenance$scope$cohort} carries \code{state}, \code{type} and
`n_governments` instead. A `govid`-named cohort reports exactly as before.} \code{n_governments} instead. A \code{govid}-named cohort reports exactly as before.}
\item{fiscal_period}{If `TRUE`, add three columns to every row: \item{fiscal_period}{If \code{TRUE}, add three columns to every row:
`fiscal_year_end` (the government's fiscal year end that survey year, an \code{fiscal_year_end} (the government's fiscal year end that survey year, an
MMDD integer such as `630`), and `period_start` and `period_end` (Dates, MMDD integer such as \code{630}), and \code{period_start} and \code{period_end} (Dates,
inclusive), the calendar months the row covers. `year` is the Census inclusive), the calendar months the row covers. \code{year} is the Census
survey year, which covers different months for different governments; survey year, which covers different months for different governments;
see "The survey-year rule" in [cog_fiscal_periods()]. The columns come see "The survey-year rule" in \code{\link[=cog_fiscal_periods]{cog_fiscal_periods()}}. The columns come
from each government-year's own `fiscal_year_end`, so a change of fiscal from each government-year's own \code{fiscal_year_end}, so a change of fiscal
year is respected, and are `NA` where the corpus has no value. The result year is respected, and are \code{NA} where the corpus has no value. The result
also gains `provenance$transformations$fiscal_period`. Defaults to also gains \code{provenance$transformations$fiscal_period}. Defaults to
`FALSE`, which returns exactly the columns and provenance this verb \code{FALSE}, which returns exactly the columns and provenance this verb
returned before the argument existed.} returned before the argument existed.}
} }
\value{ \value{
Tibble with columns `year`, `canonical_govid`, `gov_name`, Tibble with columns \code{year}, \code{canonical_govid}, \code{gov_name},
`revenue_subtype`, `category`, `amt_nominal`, optional `amt_real`, \code{revenue_subtype}, \code{category}, \code{amt_nominal}, optional \code{amt_real},
optional `amt_per_capita_nominal`, optional `amt_per_capita_real`, optional \code{amt_per_capita_nominal}, optional \code{amt_per_capita_real},
optional `pop_source`, `codes_included`, `aggregate_fallback`, `notes`, optional \code{pop_source}, \code{codes_included}, \code{aggregate_fallback}, \code{notes},
`value_source` when `complete = TRUE`, and `fiscal_year_end`, \code{value_source} when \code{complete = TRUE}, and \code{fiscal_year_end},
`period_start` and `period_end` when `fiscal_period = TRUE`. \code{period_start} and \code{period_end} when \code{fiscal_period = TRUE}.
} }
\description{ \description{
Mirror of [cog_spending()] for revenue categories. One row per Mirror of \code{\link[=cog_spending]{cog_spending()}} for revenue categories. One row per
`(year, canonical_govid, revenue_subtype, category)`. Amounts are returned \verb{(year, canonical_govid, revenue_subtype, category)}. Amounts are returned
in **full U.S. dollars** (raw Census values are in $1,000s; this verb in \strong{full U.S. dollars} (raw Census values are in $1,000s; this verb
multiplies by 1000 and records the conversion in `provenance`). multiplies by 1000 and records the conversion in \code{provenance}).
} }
+141 -140
View File
@@ -22,191 +22,192 @@ cog_spending(
) )
} }
\arguments{ \arguments{
\item{govid}{Character vector of `canonical_govid` values, or `NULL` to name \item{govid}{Character vector of \code{canonical_govid} values, or \code{NULL} to name
the cohort by `state`/`type` instead. One of `govid`, `state`, or `type` the cohort by \code{state}/\code{type} instead. One of \code{govid}, \code{state}, or \code{type}
is required.} is required.}
\item{years}{Integer vector of years.} \item{years}{Integer vector of years.}
\item{category}{Character vector of category names (from \item{category}{Character vector of category names (from
`summary_categories.category`), or `NULL` for all categories broken out \code{summary_categories.category}), or \code{NULL} for all categories broken out
one row each. The reserved value `"All Categories"` instead returns a one row each. The reserved value \code{"All Categories"} instead returns a
single summed row per `(year, canonical_govid, subtype)`, covering every single summed row per \verb{(year, canonical_govid, subtype)}, covering every
category inside the requested concept's subtype scope. It cannot be category inside the requested concept's subtype scope. It cannot be
combined with other category names, and it is not the same thing as combined with other category names, and it is not the same thing as
`expenditure_concept = "total"`: the concept chooses which subtypes are in \code{expenditure_concept = "total"}: the concept chooses which subtypes are in
scope, `"All Categories"` chooses whether rows inside that scope are scope, \code{"All Categories"} chooses whether rows inside that scope are
broken out or summed. Because the result keeps one row per broken out or summed. Because the result keeps one row per
`spend_subtype`, filtering the returned frame to \code{spend_subtype}, filtering the returned frame to
`spend_subtype == "operations"` gives an operating-expenditure total.} \code{spend_subtype == "operations"} gives an operating-expenditure total.}
\item{per_capita}{If `TRUE`, adds `amt_per_capita_nominal` (and \item{per_capita}{If \code{TRUE}, adds \code{amt_per_capita_nominal} (and
`amt_per_capita_real` when `adjust_to_year` is set) using the per-year \code{amt_per_capita_real} when \code{adjust_to_year} is set) using the per-year
Census F-33 population from `gov_population_yearly`. Result also gains Census F-33 population from \code{gov_population_yearly}. Result also gains
a `pop_source` column with values `"census_f33"` or `"unavailable"` a \code{pop_source} column with values \code{"census_f33"} or \code{"unavailable"}
(the latter for gov types 4/5 and any row whose population is missing (the latter for gov types 4/5 and any row whose population is missing
in that year).} in that year).}
\item{adjust_to_year}{Integer base year for CPI-U real-dollar conversion, \item{adjust_to_year}{Integer base year for CPI-U real-dollar conversion,
or `NULL` for nominal only.} or \code{NULL} for nominal only.}
\item{basis}{`"harmonized"` (default) sums item codes through the \item{basis}{\code{"harmonized"} (default) sums item codes through the
cross-vintage harmonization mapping (folding series-break-affected cross-vintage harmonization mapping (folding series-break-affected
codes onto a comparable target and excluding aggregate / discontinued codes onto a comparable target and excluding aggregate / discontinued
rows -- see the `harmonization` block in `cog_explain()`); `"raw"` rows -- see the \code{harmonization} block in \code{cog_explain()}); \code{"raw"}
reproduces the pre-Phase-R2 behavior (published item codes, no reproduces the pre-Phase-R2 behavior (published item codes, no
folding). On a corpus with `schema_version < 5` (no harmonization folding). On a corpus with \code{schema_version < 5} (no harmonization
tables), `basis` silently resolves to `"raw"` when left at its default tables), \code{basis} silently resolves to \code{"raw"} when left at its default
and the resolution is recorded in the provenance; explicitly passing and the resolution is recorded in the provenance; explicitly passing
`basis = "harmonized"` on such a corpus aborts. Ignored when `recipe` \code{basis = "harmonized"} on such a corpus aborts. Ignored when \code{recipe}
is set (see below).} is set (see below).}
\item{recipe}{Optional harmonization recipe id (see [cog_recipes()]) for \item{recipe}{Optional harmonization recipe id (see \code{\link[=cog_recipes]{cog_recipes()}}) for
multi-code cross-vintage series that a 1:1 harmonized_code mapping multi-code cross-vintage series that a 1:1 harmonized_code mapping
can't express (e.g. a wide-era aggregate that only splits into leaf can't express (e.g. a wide-era aggregate that only splits into leaf
codes in the modern era). Mutually exclusive with `category`. The codes in the modern era). Mutually exclusive with \code{category}. The
result's subtype column reads `"recipe"` and `category` reads the result's subtype column reads \code{"recipe"} and \code{category} reads the
recipe's label. Requires `schema_version >= 5`. A recipe query bypasses recipe's label. Requires \code{schema_version >= 5}. A recipe query bypasses
`basis` entirely (it joins `long` directly rather than going through \code{basis} entirely (it joins \code{long} directly rather than going through
the `*_annotated`/`*_annotated_harmonized` views), so the `basis` the \verb{*_annotated}/\verb{*_annotated_harmonized} views), so the \code{basis}
argument is ignored and the result's provenance reports argument is ignored and the result's provenance reports
`basis = "recipe"` with an inert `harmonization` block (`applied = \code{basis = "recipe"} with an inert \code{harmonization} block (\code{applied = FALSE}, pointing at the \code{recipe} block instead) rather than a
FALSE`, pointing at the `recipe` block instead) rather than a possibly-misleading \code{"harmonized"}/\code{"raw"} value.}
possibly-misleading `"harmonized"`/`"raw"` value.}
\item{expenditure_concept}{Which spending concept to return. Concepts are \item{expenditure_concept}{Which spending concept to return. Concepts are
defined as sets of the crosswalk's `spend_subtype` values -- never as defined as sets of the crosswalk's \code{spend_subtype} values -- never as
item-code first letters, which cannot classify correctly (prefix `Y` item-code first letters, which cannot classify correctly (prefix \code{Y}
alone spans revenue, expenditure, and balance codes): alone spans revenue, expenditure, and balance codes):
\itemize{
\item \code{"primary"} (default) -- the government's own service provision:
\code{operations} + \code{capital} + \code{assistance} subtypes.
\item \code{"direct"} -- Census's published Direct Expenditure: \code{primary} plus
\code{interest} (interest on debt) and \code{insurance_benefits} (insurance
trust benefit payments, e.g. pensions -- Census manual section
5.2.2.1 includes payments to retirees in Direct).
\item \code{"total"} -- \code{direct} plus the intergovernmental leg: payments to
local governments (\code{M} codes), to the state government (\code{L} codes,
excluding the \verb{L--} family-total rollup), and state payments to
school systems (\code{Q11}/\code{Q12}/\code{Q18}), so results gain rows with
\code{spend_subtype == "intergovernmental"}. Requires the active corpus's
\code{summary_categories} to carry M/L rows (added by cog_pipeline PR
#59); aborts with class \code{uscogdata_ig_categories_unsupported} on an
older corpus rather than silently under-reporting. Mutually
exclusive with \code{recipe} (a recipe already defines its own component
codes).
}
* `"primary"` (default) -- the government's own service provision: \strong{Do not sum \code{"total"} results across levels of government} (e.g.
`operations` + `capital` + `assistance` subtypes. state + county + city): a state's \code{M12} payment to a school district is
* `"direct"` -- Census's published Direct Expenditure: `primary` plus the same dollar the district reports as its own direct \code{E12}, so
`interest` (interest on debt) and `insurance_benefits` (insurance summing both double-counts it. This matters in particular with
trust benefit payments, e.g. pensions -- Census manual section \code{\link[=cog_geographic_rollup]{cog_geographic_rollup()}}, which sums across exactly that kind of
5.2.2.1 includes payments to retirees in Direct). multi-layer government set.
* `"total"` -- `direct` plus the intergovernmental leg: payments to
local governments (`M` codes), to the state government (`L` codes,
excluding the `L--` family-total rollup), and state payments to
school systems (`Q11`/`Q12`/`Q18`), so results gain rows with
`spend_subtype == "intergovernmental"`. Requires the active corpus's
`summary_categories` to carry M/L rows (added by cog_pipeline PR
#59); aborts with class `uscogdata_ig_categories_unsupported` on an
older corpus rather than silently under-reporting. Mutually
exclusive with `recipe` (a recipe already defines its own component
codes).
**Do not sum `"total"` results across levels of government** (e.g. In the legacy wide era (<= FY2011), some functions are published ONLY
state + county + city): a state's `M12` payment to a school district is as an aggregate-flagged family total (e.g. Corrections' \code{E04}/\code{E05}
the same dollar the district reports as its own direct `E12`, so split), which the Direct leg excludes by construction but the IG leg
summing both double-counts it. This matters in particular with deliberately keeps (see \code{inst/sql/24-ig_long.sql}). For a \code{"total"}
[cog_geographic_rollup()], which sums across exactly that kind of query, any (year, category) where this leaves intergovernmental rows
multi-layer government set. with NO Direct counterpart is flagged: the affected rows' \code{notes}
name the harmonization recipe that recovers the missing Direct
component (when one exists), and
\code{provenance$expenditure_concept_direct_suppressed} is \code{TRUE} -- the
figure in those rows is the intergovernmental leg alone, not Direct +
IG. When \code{category = "All Categories"} is combined with
\code{expenditure_concept = "total"}, this detection cannot run (it keys on
per-category rows, which all-categories mode collapses to one literal
value), so \code{expenditure_concept_direct_suppressed} is \code{NA} rather than a
possibly-false \code{FALSE}; query an explicit \code{category} to get a real
answer.}
In the legacy wide era (<= FY2011), some functions are published ONLY \item{complete}{If \code{TRUE}, fill the requested grid so that a cell the
as an aggregate-flagged family total (e.g. Corrections' `E04`/`E05` corpus does not carry still appears, labelled with \strong{why} it is
split), which the Direct leg excludes by construction but the IG leg missing, and add a \code{value_source} column to every row:
deliberately keeps (see `inst/sql/24-ig_long.sql`). For a `"total"` \itemize{
query, any (year, category) where this leaves intergovernmental rows \item \code{"reported"} — the corpus carries this cell.
with NO Direct counterpart is flagged: the affected rows' `notes` \item \code{"census_zero"} — dense-source year (\verb{<= FY2011}), cell absent:
name the harmonization recipe that recovers the missing Direct Census published \verb{$0}. \code{amt_nominal} is \code{0}.
component (when one exists), and \item \code{"not_reported"} — sparse-source year (\verb{>= FY2012}), cell absent: the
`provenance$expenditure_concept_direct_suppressed` is `TRUE` -- the government did not report, and the value is unknown. \code{amt_nominal} is
figure in those rows is the intergovernmental leg alone, not Direct + \code{NA}, \strong{not} \code{0} — writing a zero there would invent data.
IG. When `category = "All Categories"` is combined with }
`expenditure_concept = "total"`, this detection cannot run (it keys on
per-category rows, which all-categories mode collapses to one literal
value), so `expenditure_concept_direct_suppressed` is `NA` rather than a
possibly-false `FALSE`; query an explicit `category` to get a real
answer.}
\item{complete}{If `TRUE`, fill the requested grid so that a cell the The grid comes from the corpus's \code{code_set} table, scoped to each
corpus does not carry still appears, labelled with **why** it is government's own type, so a county is never filled with cells only a
missing, and add a `value_source` column to every row: state can report. Reported rows are passed through untouched.
* `"reported"` — the corpus carries this cell. Defaults to \code{FALSE} (the historical behaviour: absent cells simply do
* `"census_zero"` — dense-source year (`<= FY2011`), cell absent: not appear). Needs a corpus published from 2026-07-29 onward, which is
Census published `$0`. `amt_nominal` is `0`. when \code{representation}/\code{code_set} began shipping; aborts with class
* `"not_reported"` — sparse-source year (`>= FY2012`), cell absent: the \code{uscogdata_representation_unavailable} otherwise. Not available with
government did not report, and the value is unknown. `amt_nominal` is \code{recipe} or with \code{expenditure_concept = "total"} (class
`NA`, **not** `0` — writing a zero there would invent data. \code{uscogdata_complete_unsupported}) — neither draws its cells from
\code{code_set}.}
The grid comes from the corpus's `code_set` table, scoped to each
government's own type, so a county is never filled with cells only a
state can report. Reported rows are passed through untouched.
Defaults to `FALSE` (the historical behaviour: absent cells simply do
not appear). Needs a corpus published from 2026-07-29 onward, which is
when `representation`/`code_set` began shipping; aborts with class
`uscogdata_representation_unavailable` otherwise. Not available with
`recipe` or with `expenditure_concept = "total"` (class
`uscogdata_complete_unsupported`) — neither draws its cells from
`code_set`.}
\item{limit}{Maximum number of result rows to return, pushed into the SQL \item{limit}{Maximum number of result rows to return, pushed into the SQL
query itself (`LIMIT`/`OFFSET`) rather than applied after the full query itself (\code{LIMIT}/\code{OFFSET}) rather than applied after the full
result is materialized. `NULL` (the default) returns every matching row, result is materialized. \code{NULL} (the default) returns every matching row,
exactly as before this parameter existed. Mutually exclusive with exactly as before this parameter existed. Mutually exclusive with
`recipe` and with `complete = TRUE` -- see `offset` and `total_rows`.} \code{recipe} and with \code{complete = TRUE} -- see \code{offset} and \code{total_rows}.}
\item{offset}{Rows to skip before `limit` starts counting (0-based). \item{offset}{Rows to skip before \code{limit} starts counting (0-based).
Ignored if `limit` is `NULL`; defaults to `0L` when `limit` is set.} Ignored if \code{limit} is \code{NULL}; defaults to \code{0L} when \code{limit} is set.}
\item{state, type}{Name the cohort by predicate instead of by id: `state` is \item{state, type}{Name the cohort by predicate instead of by id: \code{state} is
a 2-letter USPS abbreviation (or a FIPS code) and `type` is one of a 2-letter USPS abbreviation (or a FIPS code) and \code{type} is one of
`"state"`, `"county"`, `"city"`, `"township"` (or the integer `0:3`) -- \code{"state"}, \code{"county"}, \code{"city"}, \code{"township"} (or the integer \code{0:3}) --
the same vocabulary, and the same internal coercion, as the same vocabulary, and the same internal coercion, as
[cog_gov_search()]. Both default to `NULL`. \code{\link[=cog_gov_search]{cog_gov_search()}}. Both default to \code{NULL}.
The cohort is then expressed as a subquery against `canonical_fips_xwalk` The cohort is then expressed as a subquery against \code{canonical_fips_xwalk}
inside each statement rather than round-tripped through R as a literal id inside each statement rather than round-tripped through R as a literal id
list. For a fleet-scale cohort that is the difference between a list. For a fleet-scale cohort that is the difference between a
301,591-character `IN` list re-parsed in 5--8 statements per call and a 301,591-character \code{IN} list re-parsed in 5--8 statements per call and a
constant-size predicate: measured at **94 ms versus 449 ms** for the same constant-size predicate: measured at \strong{94 ms versus 449 ms} for the same
FY2022 aggregate over the 20,106-government `type = "city"` cohort, within FY2022 aggregate over the 20,106-government \code{type = "city"} cohort, within
7% of the no-filter floor. 7\% of the no-filter floor.
Supplying `govid` **and** `state`/`type` INTERSECTS them -- the Supplying \code{govid} \strong{and} \code{state}/\code{type} INTERSECTS them -- the
governments in `govid` that also match the predicate -- rather than one governments in \code{govid} that also match the predicate -- rather than one
silently taking precedence. Naming no cohort at all (`govid`, `state` and silently taking precedence. Naming no cohort at all (\code{govid}, \code{state} and
`type` all `NULL`) aborts with class `uscogdata_no_cohort`. \code{type} all \code{NULL}) aborts with class \code{uscogdata_no_cohort}.
When the cohort is named by predicate, `provenance$scope$govids_found` When the cohort is named by predicate, \code{provenance$scope$govids_found}
and `govids_missing` are empty -- there is no id list to report against -- and \code{govids_missing} are empty -- there is no id list to report against --
and `provenance$scope$cohort` carries `state`, `type` and and \code{provenance$scope$cohort} carries \code{state}, \code{type} and
`n_governments` instead. A `govid`-named cohort reports exactly as before.} \code{n_governments} instead. A \code{govid}-named cohort reports exactly as before.}
\item{fiscal_period}{If `TRUE`, add three columns to every row: \item{fiscal_period}{If \code{TRUE}, add three columns to every row:
`fiscal_year_end` (the government's fiscal year end that survey year, an \code{fiscal_year_end} (the government's fiscal year end that survey year, an
MMDD integer such as `630`), and `period_start` and `period_end` (Dates, MMDD integer such as \code{630}), and \code{period_start} and \code{period_end} (Dates,
inclusive), the calendar months the row covers. `year` is the Census inclusive), the calendar months the row covers. \code{year} is the Census
survey year, which covers different months for different governments; survey year, which covers different months for different governments;
see "The survey-year rule" in [cog_fiscal_periods()]. The columns come see "The survey-year rule" in \code{\link[=cog_fiscal_periods]{cog_fiscal_periods()}}. The columns come
from each government-year's own `fiscal_year_end`, so a change of fiscal from each government-year's own \code{fiscal_year_end}, so a change of fiscal
year is respected, and are `NA` where the corpus has no value. The result year is respected, and are \code{NA} where the corpus has no value. The result
also gains `provenance$transformations$fiscal_period`. Defaults to also gains \code{provenance$transformations$fiscal_period}. Defaults to
`FALSE`, which returns exactly the columns and provenance this verb \code{FALSE}, which returns exactly the columns and provenance this verb
returned before the argument existed.} returned before the argument existed.}
} }
\value{ \value{
Tibble with columns `year`, `canonical_govid`, `gov_name`, Tibble with columns \code{year}, \code{canonical_govid}, \code{gov_name},
`spend_subtype`, `category`, `amt_nominal`, optional `amt_real`, \code{spend_subtype}, \code{category}, \code{amt_nominal}, optional \code{amt_real},
optional `amt_per_capita_nominal`, optional `amt_per_capita_real`, optional \code{amt_per_capita_nominal}, optional \code{amt_per_capita_real},
optional `pop_source`, `codes_included`, `aggregate_fallback`, `notes`, optional \code{pop_source}, \code{codes_included}, \code{aggregate_fallback}, \code{notes},
`value_source` when `complete = TRUE`, and `fiscal_year_end`, \code{value_source} when \code{complete = TRUE}, and \code{fiscal_year_end},
`period_start` and `period_end` when `fiscal_period = TRUE`. \code{period_start} and \code{period_end} when \code{fiscal_period = TRUE}.
Carries a `provenance` attribute matching `inst/schemas/provenance-v1.json`, Carries a \code{provenance} attribute matching \code{inst/schemas/provenance-v1.json},
whose `completion` block reports `applied`, `rows_filled`, and the whose \code{completion} block reports \code{applied}, \code{rows_filled}, and the
per-year `absence_means` rule that was applied. When `limit` is set, per-year \code{absence_means} rule that was applied. When \code{limit} is set,
also carries a `total_rows` attribute: the full unpaginated row count, also carries a \code{total_rows} attribute: the full unpaginated row count,
computed by the same query (`COUNT(*) OVER()`) rather than a second computed by the same query (\verb{COUNT(*) OVER()}) rather than a second
round trip -- so a caller walking pages never has to ask "how many are round trip -- so a caller walking pages never has to ask "how many are
there" separately. there" separately.
} }
\description{ \description{
One row per `(year, canonical_govid, spend_subtype, category)`. Amounts are One row per \verb{(year, canonical_govid, spend_subtype, category)}. Amounts are
returned in **full U.S. dollars** (the raw corpus stores them in $1,000s; returned in \strong{full U.S. dollars} (the raw corpus stores them in $1,000s;
this verb multiplies by 1000 so downstream code can freely rescale to this verb multiplies by 1000 so downstream code can freely rescale to
millions/billions). The conversion is recorded in the provenance attribute millions/billions). The conversion is recorded in the provenance attribute
under `transformations$units_conversion`. under \code{transformations$units_conversion}.
} }
+38 -38
View File
@@ -14,66 +14,66 @@ cog_suggestions(
) )
} }
\arguments{ \arguments{
\item{govid}{Character vector of `canonical_govid` values, or a data frame \item{govid}{Character vector of \code{canonical_govid} values, or a data frame
with a `canonical_govid` column, such as a [cog_find_peers()] or with a \code{canonical_govid} column, such as a \code{\link[=cog_find_peers]{cog_find_peers()}} or
[cog_gov_search()] result. The suggestions cover these governments as one \code{\link[=cog_gov_search]{cog_gov_search()}} result. The suggestions cover these governments as one
cohort, as they do in a verb call over the same `govid`.} cohort, as they do in a verb call over the same \code{govid}.}
\item{years}{Integer vector of requested years.} \item{years}{Integer vector of requested years.}
\item{category}{Character vector of category names from \item{category}{Character vector of category names from
`summary_categories.category`, or the reserved `"All Categories"` alone. \code{summary_categories.category}, or the reserved \code{"All Categories"} alone.
The verbs build suggestions only when a category is named, so `NULL` is The verbs build suggestions only when a category is named, so \code{NULL} is
refused here.} refused here.}
\item{flow}{`"spending"` for the suggestions [cog_spending()] would attach, \item{flow}{\code{"spending"} for the suggestions \code{\link[=cog_spending]{cog_spending()}} would attach,
or `"revenue"` for [cog_revenue()]'s.} or \code{"revenue"} for \code{\link[=cog_revenue]{cog_revenue()}}'s.}
\item{concept}{The verb's concept argument: `expenditure_concept` for \item{concept}{The verb's concept argument: \code{expenditure_concept} for
spending (`"primary"`, `"direct"` or `"total"`) or `revenue_concept` for spending (\code{"primary"}, \code{"direct"} or \code{"total"}) or \code{revenue_concept} for
revenue (`"general"` or `"total"`). `NULL`, the default, uses the verb's revenue (\code{"general"} or \code{"total"}). \code{NULL}, the default, uses the verb's
own default, `"primary"` or `"general"`. The concept changes the result own default, \code{"primary"} or \code{"general"}. The concept changes the result
only when `category = "All Categories"`, where its subtype scope decides only when \code{category = "All Categories"}, where its subtype scope decides
which recipes are candidates.} which recipes are candidates.}
\item{years_present}{Integer vector of the years in which your rows for \item{years_present}{Integer vector of the years in which your rows for
`category` have at least one row. Pass `integer(0)` when there are no \code{category} have at least one row. Pass \code{integer(0)} when there are no
rows. Years outside `years` are ignored. With `flow = "spending"` and rows. Years outside \code{years} are ignored. With \code{flow = "spending"} and
`concept = "total"`, count only rows whose `spend_subtype` is not \code{concept = "total"}, count only rows whose \code{spend_subtype} is not
`"intergovernmental"`. [cog_spending()] measures gaps on the Direct leg \code{"intergovernmental"}. \code{\link[=cog_spending]{cog_spending()}} measures gaps on the Direct leg
alone, because an intergovernmental row can survive in a year whose alone, because an intergovernmental row can survive in a year whose
Direct rows Census published only as an aggregate.} Direct rows Census published only as an aggregate.}
} }
\value{ \value{
A list with one element per suggestion, ordered by `recipe_id`, A list with one element per suggestion, ordered by \code{recipe_id},
and identical to `attr(x, "provenance")$suggestions` for the same and identical to \code{attr(x, "provenance")$suggestions} for the same
inputs. Each element is a list with `recipe_id`, `label`, inputs. Each element is a list with \code{recipe_id}, \code{label},
`available_years` (first and last year the recipe covers), `hint`, \code{available_years} (first and last year the recipe covers), \code{hint},
`trigger` (`"empty_year"` or `"suppressed_component"`), \code{trigger} (\code{"empty_year"} or \code{"suppressed_component"}),
`suppressed_amount` (full US dollars), `suppressed_years`, \code{suppressed_amount} (full US dollars), \code{suppressed_years},
`suppressed_codes`, and `ig_recipe_id` (the intergovernmental \code{suppressed_codes}, and \code{ig_recipe_id} (the intergovernmental
counterpart recipe, or `NULL`). The list is empty when nothing qualifies. counterpart recipe, or \code{NULL}). The list is empty when nothing qualifies.
} }
\description{ \description{
Builds the harmonization-recipe suggestions that [cog_spending()] and Builds the harmonization-recipe suggestions that \code{\link[=cog_spending]{cog_spending()}} and
[cog_revenue()] attach as `attr(x, "provenance")$suggestions`, without \code{\link[=cog_revenue]{cog_revenue()}} attach as \code{attr(x, "provenance")$suggestions}, without
running the verb again. Call a verb once with no `category`, filter its running the verb again. Call a verb once with no \code{category}, filter its
rows yourself, and call this when you need the suggestions for one rows yourself, and call this when you need the suggestions for one
category. category.
} }
\details{ \details{
A suggestion names a recipe (see [cog_recipes()]) that would fill a gap in A suggestion names a recipe (see \code{\link[=cog_recipes]{cog_recipes()}}) that would fill a gap in
the result. A recipe qualifies in two ways. Its `trigger` is the result. A recipe qualifies in two ways. Its \code{trigger} is
`"empty_year"` when the result has no rows in a requested year and the \code{"empty_year"} when the result has no rows in a requested year and the
recipe's own join finds rows for these governments in that year. Its recipe's own join finds rows for these governments in that year. Its
`trigger` is `"suppressed_component"` when one of the recipe's component \code{trigger} is \code{"suppressed_component"} when one of the recipe's component
codes carries dollars that the verb's own view excludes, because Census codes carries dollars that the verb's own view excludes, because Census
published them only as an aggregate or because the code is absent from published them only as an aggregate or because the code is absent from
`summary_categories`. \code{summary_categories}.
Suggestions are built only for the verbs' default `basis = "harmonized"`. Suggestions are built only for the verbs' default \code{basis = "harmonized"}.
On a corpus with `schema_version < 5` that basis is unavailable, the verbs On a corpus with \code{schema_version < 5} that basis is unavailable, the verbs
fall back to `"raw"`, and this function returns an empty list, as the fall back to \code{"raw"}, and this function returns an empty list, as the
verbs do. It also returns an empty list when nothing qualifies. verbs do. It also returns an empty list when nothing qualifies.
The verbs also print the suggestions as a message. This function returns The verbs also print the suggestions as a message. This function returns
@@ -92,6 +92,6 @@ cog_suggestions(
} }
} }
\seealso{ \seealso{
[cog_spending()], [cog_revenue()], [cog_recipes()], \code{\link[=cog_spending]{cog_spending()}}, \code{\link[=cog_revenue]{cog_revenue()}}, \code{\link[=cog_recipes]{cog_recipes()}},
[cog_explain()] \code{\link[=cog_explain]{cog_explain()}}
} }
+27 -26
View File
@@ -7,29 +7,29 @@
cog_survey_year(govid, date) cog_survey_year(govid, date)
} }
\arguments{ \arguments{
\item{govid}{Character vector of `canonical_govid` values, or a data frame \item{govid}{Character vector of \code{canonical_govid} values, or a data frame
with a `canonical_govid` column.} with a \code{canonical_govid} column.}
\item{date}{Dates, or character strings in `"YYYY-MM-DD"` form. `govid` \item{date}{Dates, or character strings in \code{"YYYY-MM-DD"} form. \code{govid}
and `date` must have the same length, or one of them must have length 1.} and \code{date} must have the same length, or one of them must have length 1.}
} }
\value{ \value{
Tibble with one row per (`govid`, `date`) pair, in input order: Tibble with one row per (\code{govid}, \code{date}) pair, in input order:
`canonical_govid`, `date`, `year` (the survey year, `NA` when it cannot \code{canonical_govid}, \code{date}, \code{year} (the survey year, \code{NA} when it cannot
be determined), `fiscal_year_end`, `period_start` and `period_end`. be determined), \code{fiscal_year_end}, \code{period_start} and \code{period_end}.
} }
\description{ \description{
Maps a date to the survey year whose fiscal period, for that government, Maps a date to the survey year whose fiscal period, for that government,
contains it. This is the reverse of [cog_fiscal_periods()]: use it to place contains it. This is the reverse of \code{\link[=cog_fiscal_periods]{cog_fiscal_periods()}}: use it to place
an event that happened on a known date against the corpus's `year`. an event that happened on a known date against the corpus's \code{year}.
} }
\details{ \details{
The date can fall in survey year Y, Y+1 or Y+2 of its own calendar year Y, The date can fall in survey year Y, Y+1 or Y+2 of its own calendar year Y,
depending on the government's fiscal year end. Each candidate is looked up depending on the government's fiscal year end. Each candidate is looked up
with the `fiscal_year_end` the corpus records for that government-year, so with the \code{fiscal_year_end} the corpus records for that government-year, so
a change of fiscal year is respected. When the government has no rows, or a change of fiscal year is respected. When the government has no rows, or
no `fiscal_year_end`, in the survey year that would cover the date, the no \code{fiscal_year_end}, in the survey year that would cover the date, the
result is `NA`; the function does not borrow another year's value. If a result is \code{NA}; the function does not borrow another year's value. If a
change of fiscal year makes two survey years' periods overlap, the earlier change of fiscal year makes two survey years' periods overlap, the earlier
survey year is returned. survey year is returned.
} }
@@ -38,17 +38,18 @@ survey year is returned.
Census assigns each government's fiscal year to a survey year by when the Census assigns each government's fiscal year to a survey year by when the
fiscal year ended. Survey year Y holds the fiscal year that ended between fiscal year ended. Survey year Y holds the fiscal year that ended between
July 1 of Y-1 and June 30 of Y. The corpus records each government-year's July 1 of Y-1 and June 30 of Y. The corpus records each government-year's
fiscal year end as `fiscal_year_end`, an MMDD integer such as `630` or fiscal year end as \code{fiscal_year_end}, an MMDD integer such as \code{630} or
`1231`. \code{1231}.
Survey year 2017 therefore covers, for a county, city or township: Survey year 2017 therefore covers, for a county, city or township:
\itemize{
* `fiscal_year_end = 630` (June 30): the fiscal year ending June 30, \item \code{fiscal_year_end = 630} (June 30): the fiscal year ending June 30,
2017, so July 2016 to June 2017. 2017, so July 2016 to June 2017.
* `930` (September 30): the fiscal year ending September 30, 2016, so \item \code{930} (September 30): the fiscal year ending September 30, 2016, so
October 2015 to September 2016. October 2015 to September 2016.
* `1231` (December 31): the fiscal year ending December 31, 2016, so \item \code{1231} (December 31): the fiscal year ending December 31, 2016, so
January to December 2016. January to December 2016.
}
A city with a December year end and a city with a June year end are both A city with a December year end and a city with a June year end are both
"2017" in the corpus, but their figures are six months apart. A September "2017" in the corpus, but their figures are six months apart. A September
@@ -68,11 +69,11 @@ rests on the documentation alone. For New York (March 31) and the 46 states
with a June 30 year end, the two rules give the same months. with a June 30 year end, the two rules give the same months.
A government can change its fiscal year end, so the periods are looked up A government can change its fiscal year end, so the periods are looked up
per government-year. Where the corpus has no `fiscal_year_end` for a per government-year. Where the corpus has no \code{fiscal_year_end} for a
government-year, or the government has no rows that year, the period is government-year, or the government has no rows that year, the period is
`NA`. Most of FY1993 is `NA`: 99% of its government-years have no usable \code{NA}. Most of FY1993 is \code{NA}: 99\% of its government-years have no usable
value in the public corpus as of November 2026. So do 5% to 11% in FY1978 value in the public corpus as of November 2026. So do 5\% to 11\% in FY1978
and FY1987 to FY1990, and under 3% in every other year. and FY1987 to FY1990, and under 3\% in every other year.
From FY2023 the source files mark some rows as estimates carried forward From FY2023 the source files mark some rows as estimates carried forward
from an earlier year. The periods here describe the survey year, not the from an earlier year. The periods here describe the survey year, not the
@@ -86,5 +87,5 @@ cog_survey_year(c("121011212191", "010000226085"), as.Date("2020-04-15"))
} }
} }
\seealso{ \seealso{
[cog_fiscal_periods()] \code{\link[=cog_fiscal_periods]{cog_fiscal_periods()}}
} }