Render a Formatted Statistics Summary Sheet
Source:R/spreadsheet_summaries.R
md_render_stats_summary.RdCreate or append a worksheet that summarises one statistic
(e.g. "pwu", "prob", "score_mean100") for a MaxDiff study across one
or more cohorts.
The function lets you
choose the metric written to the cells (
number_col),colour the cells by any other metric (
color_by_col),override number formats, colour palettes and colour‐scale break‑points, and
build a workbook incrementally via the
wbargument.
Everything is rendered with prettyxlsx, so the resulting sheet already has filters, a frozen header row, sensible column widths and hierarchical headers.
Arguments
- stats_set
A nested tibble created by
md_stats(). Must contain astatscolumn where each element is a data frame holding the statistic named instat_name.- stat_name
Character. Statistic to summarise (e.g.
"pwu","prob","score_mean100"). Must be present in every data frame insidestats_set$stats.- number_col
Character. Metric written to the cells. Defaults to
"mean".- color_by_col
Character. Metric that drives the colour scale. Defaults to
"mean". Typical alternatives are"diff_vs_avg_superiority"and"diff_vs_ref_superiority".- number_format
Character or
NULL. Excel number format applied tonumber_col. IfNULL, a sensible default is derived fromstat_nameandcolor_by_col.- breaks
Numeric vector of length three or
NULL. Low, mid and high values that anchor the colour gradient. Defaults are computed automatically whenNULL.- colors
Character vector of length three. Colours for the low, mid and high values of the gradient. Defaults to
c("#ef5d36", "white", "#50bd90").- wb
An
openxlsx::Workbookobject to append to, orNULL(default) to create a new workbook.- sheet_name
Character or
NULL. Worksheet name. IfNULL, the value ofstat_nameis used; duplicate names get an automatic numeric suffix.- headers
Character vector. Names of columns to use for constructing column headers (e.g., c("label", "level")).
- item_metadata
Optional dataframe with meta columns describing items. Must contain a character or factor column called
itemwhich will be used for joining. Must contain exactly one row per item. Typical meta columns would be item sequential index or some kind of item category.- order_by
Optional. Controls the ordering of items:
"number"— order by values innumber_colof the first cohort."color"— order by values incolor_by_colof the first cohort."item_metadata$column_name"— order by a column in theitem_metadatatable, wherecolumn_nameis the unqouted name of the column to use. Example:"item_metadata$ind".
Any of the above may be wrapped in
desc(...)to reverse the order, e.g."desc(number)","desc(color)", or"desc(item_metadata$ind)".
Cohort workflows
Individual‑level (
bayesm) – fit one model for the full sample, compute cohort‐level statistics withmd_stats(), then callmd_render_stats_summary()once per sheet you need.Aggregate (
mlogit) – fit separate models per cohort, compute statistics for each model, bind the results and pass the combinedstats_settomd_render_stats_summary().
Examples
# ---------------------------------------------------------------
# Individual‑level (bayesm) example
# ---------------------------------------------------------------
cohort_set <- example_md_data |>
haven::as_factor() |>
g6tr.cohorts::create_cohort_set(
id_col = "response_id",
grp_cols = "s_gender"
)
#> ℹ No weights provided. Using equal weights of 1.
mod_bayesm <- md_model(
example_md_parsed_data,
type = "bayesm",
mcmc = list(R = 100, keep = 1)
)
#> Z not specified
#> Table of Y values pooled over all units
#> ypooled
#> 1 2 3 4 5
#> 1504 1276 1170 1137 1103
#>
#> Starting MCMC Inference for Hierarchical Logit:
#> Normal Mixture with 1 components for first stage prior
#> 5 alternatives; 25 variables in X
#> for 213 cross-sectional units
#>
#> Prior Parms:
#> nu = 28
#> V
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13]
#> [1,] 28 0 0 0 0 0 0 0 0 0 0 0 0
#> [2,] 0 28 0 0 0 0 0 0 0 0 0 0 0
#> [3,] 0 0 28 0 0 0 0 0 0 0 0 0 0
#> [4,] 0 0 0 28 0 0 0 0 0 0 0 0 0
#> [5,] 0 0 0 0 28 0 0 0 0 0 0 0 0
#> [6,] 0 0 0 0 0 28 0 0 0 0 0 0 0
#> [7,] 0 0 0 0 0 0 28 0 0 0 0 0 0
#> [8,] 0 0 0 0 0 0 0 28 0 0 0 0 0
#> [9,] 0 0 0 0 0 0 0 0 28 0 0 0 0
#> [10,] 0 0 0 0 0 0 0 0 0 28 0 0 0
#> [11,] 0 0 0 0 0 0 0 0 0 0 28 0 0
#> [12,] 0 0 0 0 0 0 0 0 0 0 0 28 0
#> [13,] 0 0 0 0 0 0 0 0 0 0 0 0 28
#> [14,] 0 0 0 0 0 0 0 0 0 0 0 0 0
#> [15,] 0 0 0 0 0 0 0 0 0 0 0 0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 28 0 0 0 0
#> [22,] 0 0 0 0 0 0 0 0 28 0 0 0
#> [23,] 0 0 0 0 0 0 0 0 0 28 0 0
#> [24,] 0 0 0 0 0 0 0 0 0 0 28 0
#> [25,] 0 0 0 0 0 0 0 0 0 0 0 28
#> mubar
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
#> [1,] 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#> [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25]
#> [1,] 0 0 0 0 0 0 0 0 0 0 0
#> Amu
#> [,1]
#> [1,] 0.01
#> a
#> [1] 5
#>
#> MCMC Parms:
#> s= 0.476 w= 0.1 R= 100 keep= 1 nprint= 100
#>
#> initializing Metropolis candidate densities for 213 units ...
#> completed unit # 50
#> completed unit # 100
#> completed unit # 150
#> completed unit # 200
#> MCMC Iteration (est time to end - min)
#> 100 (0.0)
#> Total Time Elapsed: 0.00
stats_bayesm <- md_stats(mod_bayesm, cohort_set)
#> Warning: Cohort contains 7 respondents unknown to the model:
#>
#> "R_40B4m0P4eRx5OZr", "R_3lAnv54h4RHHV2v", "R_1f9RoTYlh6qSWfA",
#> "R_3n8Hi62m4U6Z7cX", "R_u83bGPAUc7oqIRr", "R_ZjxB4uG9OOXRG49", and
#> "R_2CdeYg6vSpk6hdY"
#> Warning: Cohort contains 2 respondents unknown to the model:
#>
#> "R_3n8Hi62m4U6Z7cX" and "R_u83bGPAUc7oqIRr"
#> Warning: Cohort contains 5 respondents unknown to the model:
#>
#> "R_40B4m0P4eRx5OZr", "R_3lAnv54h4RHHV2v", "R_1f9RoTYlh6qSWfA",
#> "R_ZjxB4uG9OOXRG49", and "R_2CdeYg6vSpk6hdY"
#> ℹ Using the first cohort in the cohort set as the reference for comparisons.
#> If you need a different reference, please reorder the cohort set accordingly.
#> • column: "population"
#> • label: "Overall population"
#> • level: "population"
# generate some item-level metadata to display
library(dplyr)
item_metadata <-
tibble(
item = levels(example_md_parsed_data$item)
) |>
mutate(
id = row_number(),
category = sample(LETTERS[1:3], n(), replace = TRUE)
)
# 1. Plain mean values
wb <- md_render_stats_summary(
stats_set = stats_bayesm,
stat_name = "score_mean100",
item_metadata = item_metadata,
order_by = "number"
)
#> ℹ No `sheet_name` provided, defaulting to "score_mean100".
# 2. Colour by superiority vs the reference cohort
wb <- md_render_stats_summary(
stats_set = stats_bayesm,
stat_name = "score_mean100",
wb = wb,
color_by_col = "diff_vs_ref_superiority",
sheet_name = "score_mean100 vs ref"
)
if (FALSE) { # \dontrun{
cloudfs::cloud_drive_write(
wb,
"summaries/maxdiff/bayesm.xlsx",
fun = openxlsx::saveWorkbook
)
# ---------------------------------------------------------------
# Aggregate (mlogit) example
# ---------------------------------------------------------------
mod_mlogit_cohort <- md_model(
example_md_parsed_data,
type = "mlogit",
cohorts = cohort_set
)
stats_mlogit <- mod_mlogit_cohort |>
rowwise() |>
mutate(stats = list(md_stats(model))) |>
ungroup()
wb2 <- md_render_stats_summary(
stats_set = stats_mlogit,
stat_name = "score_mean100",
color_by_col = "diff_vs_avg_superiority"
)
} # }