easyNIS (development version)
Select design, demographic, diagnosis, procedure, and hospital fields with
nis_vars_design(),nis_vars_demographics(),nis_vars_dx(),nis_vars_pr(), andnis_vars_hospital()on data frames and lazy tables.nis_flag_dx()andnis_flag_pr()can combine separate ICD-9 and ICD-10 definitions in one flag with experimentalsystem = "both".The descriptives and regression article shows how to use
nis_design()with gtsummary for survey summaries, group comparisons, and regression tables. The workflow test checks cohort counts and full-sample survey results.nis_join_companion()adds selected Hospital, Severity, or Diagnosis and Procedure Groups fields to lazy Core queries using checked annual keys.nis_comorbidity()now scores lazy DuckDB cohorts in bounded batches and returns the scores joined to the original query by discharge key.nis_attrition(..., .design = TRUE)counts discharges with valid survey design fields. Reuse the same eligibility rules innis_design()withcohort = !!nis_attrition_cohort(flow).The survey design article demonstrates analytic domains with
dplyr::filter()on anis_design()result and explains how filtering the lazy input can affect variance estimation.nis_outcomes()adds in-hospital mortality, length of stay, and labeled discharge disposition to an analysis, including on lazy DuckDB tables. The hospitalization outcomes article covers survey estimators and denominators.nis_open()checks annual Core files by default against HCUP’s published discharge counts, weight sums, and hospital counts for each opened year in 2012–2024. Discrepancies warn and the lazy query stays available. Files fromnis_example()skip the comparison and still receive integrity checks. Cohort extracts are expected to differ. Setcheck_release = FALSEto skip the check.Parquet opening assigns nested Hive parts to the nearest partition year and inspects each source schema once. Compatible files share a native DuckDB scan, and integer year filters can use Parquet statistics. Configure memory, threads, and spill storage before opening with
easyNIS.duckdb_config.Procedure timing, PRDAY completeness, and code-transition inventory use shared slot discovery and continue to accept zero-padded slots. Empty PRDAY summaries retain their typed columns. Procedure timing and diagnosis sensitivity avoid scratch-name collisions. DuckDB code inventory filters prefixes before expanding discharge code lists.
Survey suppression rejects malformed count cards that report multiple, negative, or fractional discharge counts.
New study reports apply discharge and hospital disclosure checks to summary headers, annual trends, and model output. Related totals are withheld when they could reveal masked figures.
The staged-file privacy guard checks the content recorded in the Git index. Probe execution, receipt validation, and readiness reporting are separate.
nis_cost()now treats negative, missing, and non-finite charges as invalid, reports their count, and retains zero charges.nis_prday_completeness()classifies factor PRDAY values from their labels and countsNaNor unparseable day values as missing, matching character, numeric, and DuckDB inputs andnis_flag_pr_timing().nis_design()counts and excludes missing logical cohorts consistently on data frames and DuckDB, including literalNAand flags initialized withNA. Typed numeric and character cohorts remain invalid, even when all missing.nis_flag_dx()andnis_flag_pr()ignore malformed slot suffixes; principal flags use the canonical slot with suffix 1.Diagnosis and procedure code-system eligibility now rejects fractional and infinite numeric
YEARindicators while preserving missing-year fallback and 2015 quarter rules.nis_reweight()supports column selection, renaming, and mutation while preserving survey weights and variance structure without restoring removed analysis columns.nis_comorbidity()ignores zero and leading-zero diagnosis slot suffixes and requires the principal diagnosis columnI10_DX1.nis_cell_counts()now rejects grouping keys namednorhospitalsto prevent cell identities from being overwritten.nis_label()treatsNaNas missing in ordinary and Haven-labelled numeric storage while retaining finite SPSS sentinels andinteger64values as displayed codes. Factors with observed raw codes use whole-vector normalization; mixed raw and labelled factors therefore label the latter as unknown codes. ExistingCode 7labels survive subsets that retain unused raw-code levels. A bareCodefactor with no raw-code levels is preserved as an existing label because its origin cannot be recovered after levels are dropped.nis_attrition()ignores input groups consistently and returns matching local and DuckDB totals for empty inputs and missing weights, includingNaN.Readiness rejects incomplete, out-of-range, Boolean, and malformed evidence while continuing to assess unrelated valid records. Invalid records use structurally recovered top-level string identities and unambiguous commit bindings; known stale records are ignored before invalid evidence is applied, and structurally valid dirty receipts cannot supersede clean proof. Nested diagnostics cannot mask a failed gate. Study receipts require unique exact fields, including the package commit and computed estimates, and reject embedded NUL bytes. Quality JSONL preserves CR, LF, CRLF, and unterminated final-line boundaries.
nis_open()now rejects selected years present in both an annual Parquet directory and a separate Hive partition, preventing duplicate rows. Hive parts within one annual dataset remain supported.nis_open()lets DuckDB combine and promote annual fields before normalizing visible names. ASCII-folded field casing is independent of annual file order; Unicode normalization collisions retain their existing coalescing behavior. Metadata-only spelling changes are applied only when the target is unique and does not collide with an existing or proposed output name under DuckDB’s identifier rules.Quality probes verify a disposable source installation and its effective namespace before measuring installed complexity. Nested packaging and coverage evidence remains unverified when it appears to pass, while measured coverage below target remains available as a failure; equal versions and library search order no longer imply source provenance (#170).
Reuse a shared roxygen template for repeated
.dataparameter documentation.nis_dx_sensitivity()now summarizes grouped inputs completely, handles empty DuckDB cohorts, and avoids aggregate collisions between outcome names.nis_ccsr_codes()rejects standard CSV records with extra or missing fields before parsing, preventing shifted code/category mappings. Quoted commas and multiline descriptions remain supported.nis_design()accepts grouped DuckDB inputs and removes input groups, including rowwise grouping, before evaluating the cohort over the full input.nis_design(keep = ...)now uses selected source values for aliases and actual column types for predicates on local and lazy DuckDB inputs. Aliases preserve source labels and cannot overwrite retained design or cost fields.nis_flag_pr_timing()now uses factor and ordered-factor procedure-day labels consistently with numeric values and DuckDB, including labels that decode to missing days.Pooled Parquet sources retain uppercase-normalized column names whenever a selected source supplies an uppercase-bearing spelling. Lowercase-only fields retain their spelling.
nis_flag_dx()andnis_flag_pr()accept named-list code definitions with per-slot exact exclusions and whole-code regular expressions. Existing character-vector prefix definitions are unchanged; prefix and regex matches can be combined in one definition.Regex flag definitions now use DuckDB’s RE2 full-match behavior for both data frames and lazy queries, preserving the supplied pattern unchanged.
nis_design(),nis_attrition(), andnis_dx_sensitivity()no longer trigger dbplyr’s “Missing values are always removed in SQL aggregation functions” warning on lazy DuckDB inputs. Results are unchanged.nis_comorbidity()now explains how to retain diagnosis columns withnis_design(keep = ...)when required ICD-10 fields are missing.nis_design()selection regressions cover character vectors,all_of(), andany_of()on lazy inputs; dollar adjustment requires both charge and cost-to-charge-ratio fields inkeep.nis_audit_code_transition()accepts several period columns inby, keeps periods with a missing component as explicit rows, and gainsoutput = "inventory"to list observed full codes by period withabsentandsparseflags (sparse_n). With severalbycolumns no unambiguous year comparison exists, soyoy_pct_changeisNAin every row. The inventory aggregates long slot rows in the database, so query width does not grow with the number of matching codes.nis_audit_code_transition()validates selected survey weights as numeric, finite, and non-missing before calculating weighted counts.nis_audit_code_transition()now accepts namedbyvectors without treating their names as period columns, and inventory output preserves a period column when it is also the selected weight column.nis_suppress()now errors when a displayed survey statistic cannot be mapped to a verifiable source count.nis_open()has an opt-inreader = "arrow"mode using the optionalarrowpackage; the default DuckDB reader is unchanged. Arrow preserves source bytes in strings rather than repairing malformed UTF-8. Such values may still fail in downstream string operations, and the reader does not automatically detect every invalid byte sequence.Split published-study probe validation into named checks while preserving receipt acceptance behavior.
EasyNIS collection errors now explain how to fix invalid UTF-8 in Parquet string columns.
The real-data workflow probe discovers diagnosis and POA fields from lazy query schemas with
colnames(), so those fields are retained bynis_design().The quality probe now saves nested
pkgcheckandgoodpracticefailure results and captured warnings in an ignored local artifact while keeping nested condition text out of its public receipt. Receipts include numeric failed-check, R CMD check error, and captured-warning counts. Prep failures and unknown check statuses are no longer reported as passing.Corrected the procedure-timing help text so manual HTML validates.
Reduce cyclomatic complexity in diagnosis sensitivity summaries and HCUP labeling without changing their results.
Project metadata
Added package-level help at
?easyNIS, links to AHRQ’s NIS documentation and survey design validation, and project status badges.Set the project license to GNU AGPL-3.0-only, update author names and ORCIDs across package metadata.
New features
Reduced cyclomatic complexity in data opening and procedure timing helpers without changing their results or lazy DuckDB query behavior.
The experimental pre-2016 ICD-9 layout notice from
nis_open()now appears once per R session.Internal helpers now split validation, cost adjustment, and synthetic fixture construction in
nis_cost()andnis_example()while preserving their existing behavior.Refactored internal CCSR mapping helpers to keep cyclomatic complexity within the repository limit without changing
nis_ccsr_codes()behavior.Refactored new-study scaffolding and model-preflight helpers to keep cyclomatic complexity within the repository limit without changing behavior.
nis_open()combines annual Parquet files with Hive year partitions and returnsYEARas integer, rejecting invalid year values with a file-specific error.nis_design()warns when annualized valid-design data represented inDQTRhave fewer than four quarters, and explains how to exclude or separately reweight those years. It also warns when a 2015 cohort contains only ICD-9-coded quarters (Q1–Q3) or only the ICD-10-coded quarter (Q4), and informs whenDQTRis missing so the 2015 split cannot be checked.nis_cost()records charge/CCR fields, CPI-U source and multipliers, base year, invalid CCR and missing charge counts, and adjusted-output meanings. Zero or negative CCR values now produceNAincost_adj(previously zero CCR produced zero cost and negative CCR produced a negative cost); one informational message reports how many rows have missing or invalid CCR (nis_design()reports cohort rows only). Usenis_cost_provenance()on its result or thenis_design()survey design.Added
nis_prday_completeness()for unweighted PRDAY completeness summaries by year and matched procedure slot.Added
nis_flag_pr_timing()for procedure timing flags.Added
nis_attrition()for cohort attrition summaries.nis_open()now reads Parquet natively with DuckDB; DuckDB-backed lazy transformations are used throughout. Theengineargument was removed entirely; callers should omit it regardless of the value they previously passed.Added
nis_audit_code_transition()to summarize code-system transitions.Added
nis_flag_dx_position()andnis_dx_sensitivity()for descriptive point estimates; these are not design-based estimates.nis_suppress()now accepts data frames withcount_col,weighted_cols, andby, and supports single-dimension complementary suppression.nis_suppress()acceptshospital_colto mask cells based on fewer than two contributing hospitals;nis_cell_counts()computes unweighted discharge and year-scoped hospital counts from record-level data or annis_design().Survey-table suppression also applies the two-hospital rule from retained
YEAR/HOSP_NISrecords, mapped to each cohort, non-missing/category, and by-group cell; it errors when that mapping is unavailable or ambiguous.nis_attrition()reportsNAdropped counts for the initial row, which has no preceding step.nis_suppress()now suppresses zero discharge counts at or below the threshold and rejects missing, non-finite, negative, or fractional data-frame count values.nis_comorbidity()now uses alignedDXPOAnfields when available.YandWcount as present on admission,NandUdo not, and other values are unknown, including invalid UTF-8 values. Missing POA columns retain the prior assumed-present behavior and now warn with the affected diagnosis slots; POA-dependent comorbidities may include conditions acquired in hospital. AHRQ requires POA to assign 18 of 38 measures and returns missing results when required POA information is absent (User Guide).medicalcoder0.10.0’s exemption mapping covers AHRQ FY2022–FY2026 and reports consistent exemption status across those releases, but does not adjust exemption status for discharge date. Exempt-code results can therefore differ slightly from AHRQ software across fiscal years.Refactored code-transition auditing, cell counts, and attrition summaries into internal helpers without changing their results or validation behavior.
Refactored
nis_design()andnis_reweight()into private validation and preparation helpers without changing survey design behavior.
Maintenance
- Readiness keeps the no-open-P0/P1-issues gate unmet when either issue query fails or returns invalid JSON.
- Readiness finds CI runs by the current commit SHA, so successful checks on another branch at the same commit are recognized while all existing success requirements remain in place.
- Refactored
nis_suppress()into internal helpers; behavior is unchanged. - Split survey suppression row mapping and cell mask decisions into smaller helpers without changing fail-closed behavior.
easyNIS 0.2.0
Highlights
- Replaced the archived API with lazy annual Parquet opening, ICD-10 prefix flags, a domain survey design, HCUP labels, CPI-adjusted charges and costs, cell suppression, and an invented six-year example fixture.
- Added a Getting started guide, a guide to porting existing NIS studies, and an analyst workflow note.
New features
Added
codemeta.json; regenerate it fromDESCRIPTIONwithRscript tools/probe/update-codemeta.Rafter changing package metadata.Quoted the
surveypackage name inDESCRIPTIONand avoided duplicate arguments when constructing the 2023 charge warning.nis_open()supports 2012 onward.nis_flag_dx()andnis_flag_pr()match literal prefixes separately in each code slot; supplied prefixes ignore case, periods, and spaces, while stored codes are compared byte for byte without text normalization, so malformed UTF-8 cannot raise a matching error.Added experimental ICD-9 prefix flags with an explicit
system = "icd9"option, metadata guards, and invented historical and split-2015 fixtures. ICD-10 remains the default.nis_comorbidity()adds AHRQ Elixhauser Refined condition flags and mortality/readmission index scores through the suggestedmedicalcoderpackage. It accepts a collected data frame or annis_design()result.nis_ccsr_codes()reads a user-supplied HCUP DXCCSR or PRCCSR reference file (Excel viareadxlor comma-separated) and returns ICD-10 codes in selected CCSR categories, optionally restricted to the default inpatient assignment. The codes can be passed tonis_flag_dx()ornis_flag_pr().
Survey design and weighting
-
nis_design()reports aggregate exclusions for invalid design fields and affected years, stores the counts in thenis_excludeddesign attribute, and documents why rows with invalidYEAR,HOSP_NIS,NIS_STRATUM, orDISCWTcannot be represented in the supplied survey design. Exclusions happen before cohort filtering and do not imply zero population weight or unbiased estimates. -
nis_design()warns when charges are entirely missing for a year or when that year has hospitals but no cohort discharges.annualizedivides by the number of distinctYEARvalues, so a partial year counts as one. - Added experimental
nis_reweight()to multiply cohort survey weights while retaining placeholder rows. It preserves column labels when rebuilding designs, including after comorbidity scoring. Weights are matched by position; call the function once. Weighted totals after reweighting are not national counts, and its placeholder variance field does not provide survey variance estimation. An optional commented WeightIt/cobalt example is in the study template.
Disclosure control
-
nis_suppress()also masks the overall (add_overall()) cell in any row where a by-group cell is masked. It marks that secondary maskMasked, unless the overall cell is itself at or below the threshold. - For
continuous2statistic rows, suppression uses the displayed output column’s non-missing count and errors when that count is missing, ambiguous, or non-finite. Other derivable cells, such as column totals across levels, are not masked; review tables before sharing.
Study template
- Quarto study reports handle empty cohorts, one-level exposures, constant outcomes, and unusable model matrices with explicit status messages. Models use complete-case preflight; single-year reports omit the year adjustment, and DOCX trend tables display years without thousands separators.
- Report caches include study definitions, external data-root identity, report inputs, output format, and rendering dependencies.
- The template includes an optional, commented propensity-weighting example; both WeightIt and cobalt must be installed to use it.
Documentation
- Added a Getting started guide covering file opening, flags, survey design, weighted tables, models, primary-cell suppression, and study scaffolding; runnable examples for exported helpers use invented fixtures, with the slower optional comorbidity example marked
donttest. - Added a vignette on porting existing NIS study code, a short tidyverse pipeline README, grouped pkgdown reference pages, and package citation metadata.
- Added issue templates, a privacy-aware pull request checklist, Contributor Covenant, security reporting guidance, and contributor instructions.
- Added CI workflows for linting, test coverage, and study-template rendering. The pkgdown site is published at https://msaadasif.github.io/easyNIS/ on pushes to
main.
Experimental and unverified
- The placeholder-row survey method is experimental and must agree with the full-data design on estimates, standard errors, and degrees of freedom.
- ICD-9 support is experimental. Historical layout facts beyond the documented 2015 Q1–Q3/Q4 split are assumptions and have not been verified against official HCUP documentation or licensed data.
- NIS 2023 layout support is experimental and UNVERIFIED against official HCUP 2023 documentation and real 2023 data. It assumes
TOTCHG_2023, the removal ofHOSP_REGIONandHOSP_DIVISION, and sequentialNIS_STRATUMbased on secondary notes.nis_open()accepts files without the geography columns and keepsTOTCHG_2023separate fromTOTCHG; queries containing it receive a once-per-session warning because HCUP’s national-estimate adjustment makes it incomparable with earlier-year charges.nis_design()andnis_cost()acceptcharges = "TOTCHG_2023"to opt in; pooling requires an explicitmutate(). Hospital and stratum IDs remain qualified by year. -
nis_comorbidity()is ICD-10 only, does not use present-on-admission values, and treatsI10_DX1as the principal diagnosis. Its output is not expected to match the Stata-derivedynel*andelixsumcolumns. Rows without a usableI10_DX*code, including ICD-9-era discharges, receiveNAand a warning rather than zeros. - HCUP CCSR file layouts are UNVERIFIED; no CCSR content is bundled. Malformed single-quoted CSV rows and non-ICD-10 codes are rejected.