Make tables and fit survey models
Source:vignettes/articles/tables-and-models.Rmd
tables-and-models.RmdThe examples use invented data.
Summarize the cohort
nis <- nis_open(nis_example(years = 2019:2020)) |>
nis_flag_dx(heart_failure = "I50")
design <- nis_design(nis, AGE >= 18, keep = c(AGE, LOS, DIED, RACE, heart_failure))
design |>
group_by(heart_failure) |>
summarise(
sampled = unweighted(n()),
discharge_total = survey_total(),
mean_los = survey_mean(LOS, na.rm = TRUE, vartype = c("se", "ci"))
)
#> # A tibble: 2 × 8
#> heart_failure sampled discharge_total discharge_total_se mean_los mean_los_se
#> <lgl> <int> <dbl> <dbl> <dbl> <dbl>
#> 1 FALSE 84 104 19.9 5.38 0.273
#> 2 TRUE 108 125. 17.3 5.66 0.229
#> # ℹ 2 more variables: mean_los_low <dbl>, mean_los_upp <dbl>sampled counts records. discharge_total
estimates the number of discharges across both years. Set the
denominator for each statistic before reviewing its disclosure risk.
table_design <- design |> select(YEAR, HOSP_NIS, heart_failure, AGE, LOS, DIED)
tbl_svysummary(table_design, by = heart_failure, include = c(AGE, LOS, DIED)) |>
nis_suppress() |>
as_gt()| Characteristic |
TRUE N = 1251,2 |
FALSE N = 1041,2 |
|---|---|---|
| Age, years | 59 (41, 76) | 65 (49, 77) |
| Length of stay, days | 6.0 (3.0, 9.0) | 5.0 (2.0, 8.0) |
| Died during hospitalization | ≤10 | ≤10 |
| 1 Median (Q1, Q3); n (%) | ||
| 2 Statistics based on unweighted n ≤10 are marked ≤10; cells contributed by fewer than two distinct year-scoped hospitals are marked '<2 hospitals', regardless of count. The discharge-count mask takes precedence when both rules apply. Dichotomous rows with a protected complement are marked 'Masked' when the displayed event passes both rules. When a categorical variable has one masked level in a column, the smallest remaining positive level is marked 'Masked'. Before sharing under the HCUP Data Use Agreement, review tables for other derivable cells. | ||
Select the table’s variables before building it. Keep
YEAR and HOSP_NIS so suppression can count
contributing hospital-years. Reuse the original design for models that
need additional variables.
Choose continuous summaries for large tables
tbl_svysummary(
table_design,
by = heart_failure,
include = c(AGE, LOS, DIED),
statistic = list(all_continuous() ~ "{mean} ({mean.std.error})")
) |>
nis_suppress() |>
as_gt()| Characteristic |
TRUE N = 1251,2 |
FALSE N = 1041,2 |
|---|---|---|
| Age, years | 58 (1) | 62 (1) |
| Length of stay, days | 5.7 (0.2) | 5.4 (0.3) |
| Died during hospitalization | ≤10 | ≤10 |
| 1 Mean (SE); n (%) | ||
| 2 Statistics based on unweighted n ≤10 are marked ≤10; cells contributed by fewer than two distinct year-scoped hospitals are marked '<2 hospitals', regardless of count. The discharge-count mask takes precedence when both rules apply. Dichotomous rows with a protected complement are marked 'Masked' when the displayed event passes both rules. When a categorical variable has one masked level in a column, the smallest remaining positive level is marked 'Masked'. Before sharing under the HCUP Data Use Agreement, review tables for other derivable cells. | ||
Choose the mean and standard error through statistic.
The default reports the median and quartiles. See the gtsummary
statistic reference.
Fit a model and estimate a contrast
fit <- survey::svyglm(LOS ~ heart_failure + AGE, design = design)
survey::svycontrast(fit, c(heart_failureTRUE = 1))
#> contrast SE
#> contrast 0.17863 0.4205
tbl_regression(fit) |> as_gt()| Characteristic | Beta | 95% CI | p-value |
|---|---|---|---|
| heart_failure | |||
| FALSE | — | — | |
| TRUE | 0.18 | -0.71, 1.1 | 0.7 |
| Age, years | -0.02 | -0.04, -0.01 | 0.001 |
| Abbreviation: CI = Confidence Interval | |||
nobs(fit)
#> [1] 192The contrast estimates the adjusted difference in mean length of
stay. Use the fitted model’s count to report the number of sampled
discharges. The N returned through tbl_regression() for a
svyglm() can be weighted. Check the fitted sample before
labeling or reporting N. Check
disclosure
Report weighted event rates
mortality_design <- design |>
filter(AGE < 65, !is.na(DIED), !is.na(heart_failure))
design_df <- survey::degf(mortality_design)
rates <- mortality_design |>
group_by(heart_failure) |>
summarise(
events_sampled = unweighted(sum(DIED)),
discharges_sampled = unweighted(n()),
events_weighted = survey_total(DIED, vartype = NULL),
discharges_weighted = survey_total(vartype = NULL),
rate = survey_mean(DIED, vartype = c("se", "ci"), df = design_df)
)Filtering the design preserves the sample structure for the under-65 domain. The rate is the weighted share of discharges with an in-hospital death, on a 0–1 scale. The rate and model below use the same complete cases. Check additional covariates for missingness if you add them.
Before displaying the rates or their counts, check support for both deaths and discharges without a death. An absent outcome level has zero support. Mask the rate, its uncertainty, and all counts together when either outcome level is protected.
support <- nis_cell_counts(mortality_design, by = c(heart_failure, DIED)) |>
group_by(heart_failure) |>
summarise(
min_sampled = if (n() == 2L) min(n) else 0L,
min_hospitals = if (n() == 2L) min(hospitals) else 0L,
.groups = "drop"
)
rates_for_review <- rates |>
left_join(support, by = "heart_failure") |>
nis_suppress(
count_col = min_sampled,
hospital_col = min_hospitals,
weighted_cols = c(events_sampled, discharges_sampled, events_weighted,
discharges_weighted, rate, rate_se, rate_low, rate_upp)
) |>
select(-min_sampled, -min_hospitals)
rates_for_review
#> # A tibble: 2 × 9
#> heart_failure events_sampled discharges_sampled events_weighted
#> <lgl> <chr> <chr> <chr>
#> 1 FALSE ≤10 ≤10 ≤10
#> 2 TRUE ≤10 ≤10 ≤10
#> # ℹ 5 more variables: discharges_weighted <chr>, rate <chr>, rate_se <chr>,
#> # rate_low <chr>, rate_upp <chr>Complementary suppression is on by default: if one exposure group is masked, a second group is masked too, so the masked group can’t be recovered from the cohort total reported elsewhere. Still review overlapping tables, totals, and contrasts for deductions from masked cells before sharing. See disclosure review.
Estimate adjusted probabilities and a reference difference
survey::svypredmeans() takes an adjustment model whose
formula omits the exposure. It adds the exposure as a main effect, then
averages the predicted probabilities at each exposure level over the
same weighted age distribution in the analytic domain.
survey::svycontrast() uses the covariance of the margins to
estimate the difference from the no-heart-failure reference.
adjustment <- survey::svyglm(
DIED ~ AGE,
design = mortality_design,
family = quasibinomial()
)
margins <- survey::svypredmeans(
adjustment, ~heart_failure, predictat = c(FALSE, TRUE)
)
estimates <- survey::svycontrast(
margins,
list(
"No heart failure" = c("FALSE" = 1),
"Heart failure" = c("TRUE" = 1),
"Difference vs. no heart failure" = c("FALSE" = -1, "TRUE" = 1)
)
)
limits <- confint(estimates, df = design_df)
adjusted <- tibble::tibble(
term = names(coef(estimates)),
estimate = as.numeric(coef(estimates)),
std.error = as.numeric(survey::SE(estimates)),
conf.low = limits[, 1],
conf.high = limits[, 2]
)
adjusted
#> # A tibble: 3 × 5
#> term estimate std.error conf.low conf.high
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 No heart failure 0.0515 0.0284 -0.00814 0.111
#> 2 Heart failure 0.0285 0.0210 -0.0157 0.0727
#> 3 Difference vs. no heart failure -0.0230 0.0415 -0.110 0.0642Multiply the difference by 100 to report percentage points. The adjusted probabilities and contrast above are for invented data. Before reporting results from a study, check the outcome and exposure cells in the fitted sample and assess what the predictions and contrast could reveal together with the other outputs.
Apply prespecified reweights
reweighted <- nis_reweight(design, ifelse(AGE >= 65, 1.2, 0.9))
summarise(reweighted, mean_los = survey_mean(LOS))
#> # A tibble: 1 × 2
#> mean_los mean_los_se
#> <dbl> <dbl>
#> 1 5.41 0.151These factors illustrate how to apply multipliers. In a study, define the target population and assess overlap and balance for the chosen weighting method. The standard errors treat the supplied factors as fixed. Use the original design for national discharge counts. Multiplying by analysis weights changes what the totals estimate. Annualization alone divides every design weight by the same number of years.