Skip to contents

Scenario: Planning a Realistic 2-Level School Intervention Study

Real educational and organizational multilevel studies rarely fit textbook idealized assumptions: cluster sizes vary across schools, researchers often power for a cross-level interaction (e.g., whether a school-level intervention z1 moderates the slope of a student-level covariate x1), and level-1 residuals can exhibit heavy tails.

This walkthrough takes a realistic study from plain English all the way to an AST-verified standalone simulation script, executed power summary, visualization, and reproducible study bundle—running 100% offline.

1. Plain-English Intent to Verified spec_ir

library(specshiny)

prompt <- paste(
  "2-level power analysis for the cross-level interaction between x1 and z1 of 0.35",
  "with 40 schools, 18 students per school, cluster size sd 5, ICC 0.20,",
  "level-2 z1 effect 0.25, random slope for x1 with sd 0.20,",
  "t-distributed errors df 5, 12 replications"
)

tr <- nl_to_spec(prompt)
tr$spec
#> 
#> ── spec_ir v1.2.0 [valid] ──
#> 
#> Title: 2-Level School Linear Power Simulation (Random Slopes)
#> Design: power_analysis | Estimator: lmer
#> Hierarchy: 2-level (40 schools x 18 students = 720 total; ICC = 0.2)
#> Outcome: y (gaussian, link = identity)
#> Predictors: x1 [L1, normal, beta=0.25], z1 [L2, normal, beta=0.25]
#> Random Slopes: x1 (sd=0.2)
#> Simulation: 12 reps | alpha = 0.05 | seed = 2026 | grid: none

Inspect the synthesized mathematical model and LaTeX equation:

math <- spec_to_math(tr$spec)
cat(math$formula, "\n\n")
#> y ~ x1 + z1 + x1:z1 + (1 + x1 | school)
cat(math$text, "\n")
#> Model: y ~ x1 + z1 + x1:z1 + (1 + x1 | school) (gaussian, identity link | Errors: Student-t(df=5))
#> Structure: 2-level (40 schools x unbalanced Normal(mean=18, sd=5) students, expected N = 720, ICC = 0.20) | Estimator: lmer
#> Focal term: x1:z1 (beta = 0.35) | Complete data (no missingness)

2. Conversational Refinement with Undo/Redo History

Track design iterations with spec_history() as we add a cluster-count power sweep across 25, 45, and 65 schools:

hist <- spec_history(tr$spec)

ref1 <- refine_spec(tr$spec, "sweep clusters across 25, 45, 65")
history_push(hist, ref1$spec, label = "Add cluster count grid")
ref1$diff
#> 
#> ── spec_diff (1 change across 1 section)
#> ✔ simulation.parameter_grid.n_clusters: added (c(25, 45, 65))

# Inspect what happens if we also test 15% MAR attrition, then undo it
ref2 <- refine_spec(ref1$spec, "set 15% MAR missingness")
history_push(hist, ref2$spec, label = "Test 15% MAR")
history_summary(hist)
#>   index is_current                  label n_changes
#> 1     1      FALSE  Initial specification         0
#> 2     2      FALSE Add cluster count grid         1
#> 3     3       TRUE           Test 15% MAR         4

# Undo back to the complete-data sweep cleanly
restored <- history_undo(hist)
study_spec <- restored$spec
study_spec$missingness$mechanism
#> [1] "none"

3. Dynamic Minimal UI Control Surface

Notice how spec_to_controls() automatically exposes ONLY the active parameters for this complex design—including cluster_size_sd, error_df, inter_beta_x1__z1, slope_sd_x1, corr_1_2, and grid_n_clusters—while still hiding irrelevant controls like n_obs, error_skew, missing_rate, or outcome_link:

desc <- spec_to_controls(study_spec)
desc
#> 
#> ── spec_ui_descriptor (26 active controls across 6 sections)
#> • Data Hierarchy (5): n_clusters, cluster_size, cluster_size_dist, icc,
#>   cluster_size_sd
#> • Outcome Model (4): outcome_family, residual_sd, error_dist, error_df
#> • Predictors & Fixed Effects (6): pred_beta_x1, pred_sd_x1, pred_centering_x1,
#>   pred_beta_z1, pred_sd_z1, pred_centering_z1
#> • Fixed & Random Effects (5): effects_intercept, focal_predictor,
#>   inter_beta_x1__z1, slope_sd_x1, corr_1_2
#> • Missingness (1): missing_mechanism
#> • Simulation & Estimator (5): n_reps, alpha, seed, estimator_reml,
#>   grid_n_clusters

4. Compiling, AST-Verifying, and Executing the Power Study

Compile study_spec into a standalone R script (automatically verified by verify_compiled_r_ast()), execute it in a fresh isolated environment, and inspect the empirical power table across cluster counts:

sim_file <- tempfile(fileext = ".R")
code <- compile_r_script(study_spec, file = sim_file, run_on_source = TRUE)
verify_compiled_r_ast(code)
#> ✔ AST safety verification PASSED (8 expressions, 82 unique whitelisted calls).

has_lme4 <- requireNamespace("lme4", quietly = TRUE)
if (has_lme4) {
  sim_env <- new.env(parent = globalenv())
  invisible(capture.output(sys.source(sim_file, envir = sim_env)))
  power_tbl <- sim_env$results$summary
  power_tbl
}
#> Loading required package: Matrix
#>   n_clusters n_reps n_converged true_effect mean_est    bias emp_se mean_se
#> 1         25     12          10        0.35   0.3384 -0.0116 0.1160  0.0794
#> 2         45     12          11        0.35   0.3525  0.0025 0.0578  0.0499
#> 3         65     12          12        0.35   0.3546  0.0046 0.0317  0.0376
#>     rmse power coverage
#> 1 0.1106     1   0.8000
#> 2 0.0551     1   0.9091
#> 3 0.0307     1   1.0000
unlink(sim_file)

5. Visualizing the Empirical Power Curve

if (has_lme4 && requireNamespace("ggplot2", quietly = TRUE)) {
  ggplot2::ggplot(power_tbl, ggplot2::aes(x = n_clusters, y = power)) +
    ggplot2::geom_line(color = "#264653", linewidth = 1) +
    ggplot2::geom_point(color = "#264653", size = 3) +
    ggplot2::geom_hline(yintercept = 0.80, linetype = "dashed", color = "#6e7f8d") +
    ggplot2::scale_y_continuous(limits = c(0, 1)) +
    ggplot2::labs(
      title = "Cross-Level Interaction Power Curve (x1:z1)",
      subtitle = "Unbalanced clusters (SD = 5), random slope, Student-t(df = 5) errors",
      x = "Number of Schools (J)",
      y = "Empirical Power (alpha = 0.05)"
    ) +
    ggplot2::theme_minimal(base_size = 11)
}

6. Exporting a Verified Study Bundle

Package the validated specification, standalone script, Quarto report, and SHA-256 manifest into a self-contained reproducible archive:

bundle_dir <- file.path(tempdir(), "specshiny_mlm_walkthrough_bundle")
export_spec_bundle(study_spec, bundle_dir, overwrite = TRUE)
verify_spec_bundle(bundle_dir)
#> ✔ Bundle verification PASSED (SHA-256 checksums, spec_ir validation, and static AST check all clean).
unlink(bundle_dir, recursive = TRUE)