compute_summary_stats <- function(x) {
tibble(
N = sum(!is.na(x)),
Mean = mean(x, na.rm = TRUE),
`Std Dev` = sd(x, na.rm = TRUE),
Skew = e1071::skewness(x, na.rm = TRUE),
Kurtosis = e1071::kurtosis(x, na.rm = TRUE),
Min = min(x, na.rm = TRUE),
`5%` = quantile(x, 0.05, na.rm = TRUE, names = FALSE),
`25%` = quantile(x, 0.25, na.rm = TRUE, names = FALSE),
`50%` = quantile(x, 0.50, na.rm = TRUE, names = FALSE),
`75%` = quantile(x, 0.75, na.rm = TRUE, names = FALSE),
`95%` = quantile(x, 0.95, na.rm = TRUE, names = FALSE),
Max = max(x, na.rm = TRUE)
)
}
metric_order <- c("N", "Mean", "Std Dev", "Skew", "Kurtosis",
"Min", "5%", "25%", "50%", "75%", "95%", "Max")
# Contrast two or more named groups side by side, one column per group.
summary_table <- function(...) {
groups <- list(...)
purrr::imap_dfr(groups, \(x, nm) compute_summary_stats(x) |> mutate(Group = nm)) |>
pivot_longer(-Group, names_to = "Metric", values_to = "Value") |>
pivot_wider(names_from = Group, values_from = Value) |>
mutate(Metric = factor(Metric, levels = metric_order)) |>
arrange(Metric)
}
# Summarize a single vector (e.g. a vector of z-scores).
single_summary_table <- function(x) {
compute_summary_stats(x) |>
pivot_longer(everything(), names_to = "Metric", values_to = "Value") |>
mutate(Metric = factor(Metric, levels = metric_order)) |>
arrange(Metric)
}