Skip to contents

specshiny v0.4.0 introduces three practitioner-oriented capabilities built on top of the same schema-validated IR (spec_ir v1.2.0) and AST-verified compilation pipeline:

  1. Longitudinal growth-curve designs (design_type = "longitudinal_growth") with explicit wave schedules (time_points, time_spacing), random intercepts and random time slopes, stationary within-subject AR(1) residual autocorrelation (outcome$ar1_rho), and strictly monotone post-baseline dropout (missingness$mechanism = "monotone_dropout").
  2. Multi-scenario design comparison (compare_specs()) quantifying total sample size NN, cluster design effect (DEFF\mathrm{DEFF}), effective sample size (NeffN_{\mathrm{eff}}), variance decomposition, semantic IR diffs, and optional comparative Monte Carlo power.
  3. An extensible domain template registry (list_spec_templates(), use_spec_template(), register_spec_template(), unregister_spec_template()) that gates every registered template through both assert_valid_spec_ir() and verify_compiled_r_ast().

1. Longitudinal Growth Curves with AR(1) & Monotone Dropout

Plain-English descriptions of repeated-measures growth studies compile directly into spec_ir v1.2.0 using the offline translator_rule() backend:

prompt <- paste(
  "Longitudinal growth curve simulation with 120 subjects across 5 waves,",
  "ICC 0.4, AR(1) correlation 0.4, growth slope 0.35, random slope for time,",
  "treatment effect 0.25, 25% monotone dropout, 200 replications"
)

tr <- nl_to_spec(prompt)
tr$spec
#> 
#> ── spec_ir v1.2.0 [valid] ──
#> 
#> Title: 2-Level Subject Linear Longitudinal Growth Study (Random Slopes,
#> monotone_dropout Missingness)
#> Design: longitudinal_growth | Estimator: lmer
#> Hierarchy: Longitudinal (120 subjects x 5 waves = 600 total; ICC = 0.4)
#> Outcome: y (gaussian, link = identity, AR(1) rho = 0.4)
#> Predictors: time [L1, time, beta=0.35], treatment [L2, binary, beta=0.25]
#> Random Slopes: time (sd=0.2)
#> Missingness: monotone_dropout (25% on outcome)
#> Simulation: 200 reps | alpha = 0.05 | seed = 2026 | grid: none

Refinements update wave counts, time schedules, autocorrelation, and dropout rates while maintaining all statistical sanity guardrails (such as keeping abs(ar1_rho) < 0.95 and synchronizing time_points, cluster_size, and time_spacing):

ref <- refine_spec(tr$spec, "increase to 6 waves and set AR(1) rho to 0.55")
ref$diff
#> 
#> ── spec_diff (4 changes across 2 sections)
#> • hierarchy.cluster_size: 5 -> 6
#> • hierarchy.time_points: 5 -> 6
#> • hierarchy.time_spacing: c(0, 1, 2, 3, 4) -> c(0, 1, 2, 3, 4, 5)
#> • outcome.ar1_rho: 0.4 -> 0.55
spec_to_math(ref$spec)$latex
#> [1] "\\begin{aligned}\n\\text{y}_{ij} &= \\beta_0 + \\beta_{1}\\,\\text{time}_{ij} + \\beta_{2}\\,\\text{treatment}_{j} + u_{0j} + u_{1j}\\,\\text{time}_{ij} + \\varepsilon_{ij}, \\quad \\varepsilon_{ij} \\sim \\mathcal{N}(0, 1^2) \\\\\n(u_{0j}, u_{1j})^\\top &\\sim \\mathcal{N}(\\mathbf{0}, \\boldsymbol{\\Sigma}), \\quad \\text{diag}(\\boldsymbol{\\Sigma})^{1/2} = (0.8165, 0.2000), \\; J = 120, \\; n_j = 6 \\\\\n\\text{Parameters:} &\\quad \\beta_0 = 0, \\; \\beta_{1} = 0.35, \\; \\beta_{2} = 0.25 \\\\\n\\text{Autocorrelation:} &\\quad \\text{Corr}(\\varepsilon_{tj}, \\varepsilon_{t-1,j}) = \\rho = 0.55 \\; (\\text{AR(1)}, \\; T = 6 \\text{ waves}) \\\\\n\\text{Missingness:} &\\quad \\text{Monotone dropout on } \\text{y} \\; (\\text{cumulative attrition} = 0.25)\n\\end{aligned}"

Notice that spec_to_controls() synthesizes longitudinal-specific controls (time_points, ar1_rho, and "monotone_dropout" in the missingness selector) while omitting inapplicable cross-sectional cluster-size distribution widgets:

desc <- spec_to_controls(ref$spec)
desc$sections$hierarchy$controls[[2]]$id
#> [1] "time_points"
desc$sections$outcome$controls[[4]]$id
#> [1] "ar1_rho"
desc$available_grid_axes
#> [1] "n_clusters"   "icc"          "focal_effect" "residual_sd"  "ar1_rho"     
#> [6] "missing_rate"

Compiling and Verifying AR(1) & Monotone Dropout Behavior

compile_r_script() deterministically emits standalone R code (verified via verify_compiled_r_ast(strict = TRUE)) implementing stationary AR(1) within- subject innovations and strictly monotone wave-by-wave attrition:

sp_demo <- use_spec_template(
  "longitudinal_growth_ar1",
  n_clusters = 150L,
  ar1_rho = 0.50,
  n_reps = 2L
)

r_script <- compile_r_script(sp_demo)
ast_report <- verify_compiled_r_ast(r_script)
c(ast_safe = ast_report$safe, expressions = ast_report$n_expressions)
#>    ast_safe expressions 
#>           1           8

# Source the compiled script in an isolated environment and inspect one draw
f_tmp <- tempfile(fileext = ".R")
writeLines(r_script, f_tmp)
sim_env <- new.env(parent = baseenv())
invisible(capture.output(sys.source(f_tmp, envir = sim_env)))
#> Loading required package: Matrix
unlink(f_tmp)

dat <- sim_env$simulate_one_dataset(sim_env$cfg)
miss_mat <- matrix(is.na(dat$y), nrow = sp_demo$hierarchy$n_clusters,
                   ncol = sp_demo$hierarchy$time_points, byrow = TRUE)

c(
  wave1_missing = sum(miss_mat[, 1L]),
  all_subjects_strictly_monotone = all(apply(miss_mat, 1L, function(r) all(diff(as.integer(r)) >= 0L))),
  final_wave_dropout_rate = round(mean(miss_mat[, ncol(miss_mat)]), 3)
)
#>                  wave1_missing all_subjects_strictly_monotone 
#>                          0.000                          1.000 
#>        final_wave_dropout_rate 
#>                          0.187

2. Comparing Competing Designs with compare_specs()

When designing a study, researchers routinely trade off sample size, cluster allocation, cluster-size imbalance, and repeated-measures structure. compare_specs() evaluates two or more validated spec_ir objects side by side using the Kish / Eldridge-Ashby-Kerry design effect:

DEFF=1+(n‾j(1+CV2)−1)ICC,Neff=NDEFF.\mathrm{DEFF} = 1 + \left(\bar{n}_j (1 + \mathrm{CV}^2) - 1\right)\mathrm{ICC}, \qquad N_{\mathrm{eff}} = \frac{N}{\mathrm{DEFF}}.

s_ols  <- use_spec_template("factorial_ols", n_obs = 400L)
s_crt  <- use_spec_template("cluster_rct", n_clusters = 40L, cluster_size = 10L)
s_mlm  <- use_spec_template("cross_level_mlm", n_clusters = 40L, cluster_size = 10L, cluster_size_sd = 4)
s_long <- use_spec_template("longitudinal_growth_ar1", n_clusters = 80L, ar1_rho = 0.45)

cmp <- compare_specs(
  ols = s_ols,
  balanced_crt = s_crt,
  unbalanced_mlm = s_mlm,
  longitudinal_ar1 = s_long
)

cmp
#> 
#> ── spec_comparison (4 scenarios; baseline = 'ols') ──
#> 
#>          scenario         design_type total_n icc   deff  n_eff focal_effect
#>               ols      monte_carlo_lm     400 0.0 1.0000 400.00         0.45
#>      balanced_crt      power_analysis     400 0.2 2.8000 142.86         0.35
#>    unbalanced_mlm       two_level_mlm     403 0.2 3.1091 129.62         0.30
#>  longitudinal_ar1 longitudinal_growth     400 0.4 2.6000 153.85         0.25
#>             missingness ar1_rho
#>                    none      NA
#>                    none      NA
#>                    none      NA
#>  monotone_dropout (25%)    0.45
#> ── Differences vs. baseline ('ols')
#> • balanced_crt: 30 IR path diff(s) | delta N_eff = -257.1, delta DEFF = +1.800
#> • unbalanced_mlm: 48 IR path diff(s) | delta N_eff = -270.4, delta DEFF =
#>   +2.109
#> • longitudinal_ar1: 37 IR path diff(s) | delta N_eff = -246.2, delta DEFF =
#>   +1.600

Extract the full comparison table with as.data.frame() or examine metric deltas relative to the baseline scenario:

as.data.frame(cmp)[, c("scenario", "total_n", "cluster_size_cv", "icc", "deff", "n_eff", "n_controls")]
#>           scenario total_n cluster_size_cv icc   deff  n_eff n_controls
#> 1              ols     400          0.0000 0.0 1.0000 400.00         17
#> 2     balanced_crt     400          0.0000 0.2 2.8000 142.86         20
#> 3   unbalanced_mlm     403          0.3835 0.2 3.1091 129.62         25
#> 4 longitudinal_ar1     400          0.0000 0.4 2.6000 153.85         23
cmp$deltas
#>           scenario delta_total_n delta_deff delta_n_eff delta_n_controls
#> 1              ols             0     0.0000        0.00                0
#> 2     balanced_crt             0     1.8000     -257.14                3
#> 3   unbalanced_mlm             3     2.1091     -270.38                8
#> 4 longitudinal_ar1             0     1.6000     -246.15                6
#>   n_changed_paths
#> 1               0
#> 2              30
#> 3              48
#> 4              37

Setting run_power = TRUE runs a bounded pure-R preview simulation for every scenario under a shared random seed so you can inspect comparative power, bias, and standard errors alongside analytical efficiency:

cmp_pwr <- compare_specs(
  ols = s_ols,
  balanced_crt = s_crt,
  run_power = TRUE,
  preview_reps = 10L,
  seed = 2026L
)
as.data.frame(cmp_pwr)[, c("scenario", "total_n", "n_eff", "focal_effect", "est_power", "est_mean_se")]
#>       scenario total_n  n_eff focal_effect est_power est_mean_se
#> 1          ols     400 400.00         0.45       0.6      0.1980
#> 2 balanced_crt     400 142.86         0.35       0.4      0.1883

3. Built-In & Custom Domain Templates

specshiny ships five immutable built-in templates spanning experimental, multilevel, longitudinal, and generalized linear designs:

list_spec_templates()[, c("name", "source", "category", "design_type", "estimator")]
#>                      name  source     category         design_type estimator
#> 1             cluster_rct builtin experimental      power_analysis      lmer
#> 2         cross_level_mlm builtin   multilevel       two_level_mlm      lmer
#> 3 longitudinal_growth_ar1 builtin longitudinal longitudinal_growth      lmer
#> 4          logistic_power builtin          glm      power_analysis     glmer
#> 5           factorial_ols builtin experimental      monte_carlo_lm        lm

Instantiate any template with parameter overrides (by control ID, shorthand field name, or dotted IR path) and optional natural-language refinement:

s_custom <- use_spec_template(
  "longitudinal_growth_ar1",
  overrides = list("outcome.ar1_rho" = 0.60, title = "Quarterly Clinical Trial"),
  time_spacing = c(0, 3, 6, 9, 12),
  n_clusters = 100L,
  refine = "add 20% monotone dropout"
)
s_custom
#> 
#> ── spec_ir v1.2.0 [valid] ──
#> 
#> Title: Quarterly Clinical Trial
#> Design: longitudinal_growth | Estimator: lmer
#> Hierarchy: Longitudinal (100 subjects x 5 waves = 500 total; ICC = 0.4)
#> Outcome: y (gaussian, link = identity, AR(1) rho = 0.6)
#> Predictors: time [L1, time, beta=0.3], treatment [L2, binary, beta=0.15]
#> Random Slopes: time (sd=0.25)
#> Missingness: monotone_dropout (20% on outcome)
#> Simulation: 300 reps | alpha = 0.05 | seed = 2026 | grid: none

Teams can register their own reusable templates with register_spec_template(). Registration is strictly gated by both assert_valid_spec_ir() and verify_compiled_r_ast(compile_r_script(spec), strict = TRUE), so invalid or unsafe specifications can never enter the registry:

register_spec_template(
  name = "quarterly_clinical_growth",
  spec = s_custom,
  description = "5-wave quarterly growth curve with AR(1) rho = 0.60 and 20% monotone dropout.",
  category = "clinical"
)

list_spec_templates(category = "clinical")[, c("name", "source", "category", "design_type")]
#>                        name source category         design_type
#> 1 quarterly_clinical_growth custom clinical longitudinal_growth

# Instantiate directly from the custom template
s_run <- use_spec_template("quarterly_clinical_growth", n_clusters = 140L)
spec_total_n(s_run)
#> [1] 700

# Clean up session registry
unregister_spec_template("quarterly_clinical_growth")