Skip to contents

Overview

Once your survey data is tidied with lx_parse_data(), each experiment can be fit with the Bayesian model implemented in Stan and wrapped by lx_fit(). This vignette shows how to run the model and inspect the resulting posterior draws and diagnostics.

We assume you have worked through 1_data_format_and_parsing.Rmd and have a parsed object ready to go. The examples below use the bundled example_srv_lx dataset.

Selecting an experiment to fit

lx_parse_data() returns a tibble with one row per experiment and a data column that stores the parsed tibble for that experiment. Pick the bundle you want to model (here, the “pets” experiment):

parsed <- lx_parse_data(
  example_srv_lx,
  n_insens = 4,
  id_col = response_id,
  treatment = m2_list_treatment,
  private = "m2_list_{exp}_private",
  public = "m3_list_{exp}_public",
  majority = "m3_list_{exp}_majority",
  predictors = starts_with("d_"),
  treatment_coding = c(control = "ctrl", treatment = "trt")
)
pets_data <- 
  parsed$data$pets |> 
  lx_set_metadata(statement = "Adopt a shelter pet this year")
pets_data
#> 
#> ── List Experiment Data ────────────────────────────────────────────────────────
#> Respondents: 500
#> Private complete cases: 500
#> Public complete cases: 500
#> Control statements: 4
#> Predictors: "d_gender", "d_age", "d_hhincome"
#> Metadata:
#> - statement: "Adopt a shelter pet this year"
#> - experiment: "pets"
#>     private                    public                    majority               
#>     0 1 2 3 4 5    n           a d u    n                a d u    n             
#> ctr ▁ ▅ █ ▄ ▂    262       ctr ▂ █ ▂  262            ctr ▃ █ ▄  262             
#>                                                                                 
#> trt ▂ ▅ █ ▇ ▃ ▁  238       trt ▂ █ ▃  238            trt ▄ █ ▃  238             
#> # A tibble: 500 × 7
#>    id     weight treatment private public   majority predictors$d_gender $d_age
#>    <chr>   <dbl> <fct>       <int> <fct>    <fct>    <fct>               <fct> 
#>  1 LX0001      1 treatment       5 disagree disagree female              18-30 
#>  2 LX0002      1 treatment       4 disagree unsure   female              46-64 
#>  3 LX0003      1 treatment       2 disagree agree    male                46-64 
#>  4 LX0004      1 treatment       1 unsure   disagree female              46-64 
#>  5 LX0005      1 control         2 agree    agree    female              46-64 
#>  6 LX0006      1 treatment       1 unsure   disagree female              65+   
#>  7 LX0007      1 control         1 disagree disagree male                31-45 
#>  8 LX0008      1 treatment       2 unsure   disagree male                46-64 
#>  9 LX0009      1 treatment       0 disagree disagree male                46-64 
#> 10 LX0010      1 control         2 disagree disagree male                46-64 
#> # ℹ 490 more rows
#> # ℹ 1 more variable: predictors$d_hhincome <fct>
#> ────────────────────────────────────────────────────────────────────────────────

Each parsed object knows how many insensitive statements were included in the experiment (stored in the n_insens attribute), along with standardized treatment/response columns and a predictors list-column ready for modeling.

Running lx_fit()

lx_fit() wraps the Stan sampler. At minimum you supply the parsed data. Adjust iter, chains, and cores like any Stan model; set seed for reproducibility. The example below mirrors the model stored in example_lx_model.

model_pets <- lx_fit(
  pets_data,
  iter = 100,
  chains = 2,
  cores = 2,
  seed = 123
)

model_pets

Two lx_fit() options are especially important for public-response handling:

  • unsure_coding controls what to do with "unsure" in public/majority responses: "disagree" recodes to 0, while "remove" excludes those rows. The default is "disagree".
  • use_public controls which treatment arm contributes to the public-data model part: "control" (default), "both", or "treatment". The default is usually preferred; "treatment" is generally not recommended because seeing the sensitive item in the count question can influence direct public answers.
model_pets_2 <- lx_fit(
  pets_data,
  unsure_coding = "remove",
  use_public = "both",
  iter = 100,
  chains = 2,
  cores = 2
)

During fitting you will see CLI messages showing Stan progress and draw extraction.

Inspecting draws and diagnostics

The lx_model carries posterior draws for both public and private agreement probabilities, plus summaries:

model_pets
#> 
#> ── List Experiment Model ───────────────────────────────────────────────────────
#> • prob_public: 500 x 200 (respondents x iterations)
#> • prob_private: 500 x 200 (respondents x iterations)
#> • response_public: <tbl_df/tbl/data.frame>
#> • response_private: <tbl_df/tbl/data.frame>
#> • response_majority: <tbl_df/tbl/data.frame>
#> • draws_summary: <draws_summary/tbl_df/tbl/data.frame>
#> • rhat_summary: <tbl_df/tbl/data.frame>
#> • sim_public: 262 x 200 (respondents x iterations)
#> • sim_private: 500 x 200 (respondents x iterations)
#> • data: <lx_data/tbl_df/tbl/data.frame>
#> • n_insens: 4
#> • blueprint: <formula_blueprint/hardhat_blueprint>
#> • statement: "Adopt a shelter pet this year"
#> • experiment: "pets"
#> ! Model did not converge properly; found NA and/or > 1.05 Rhat values
#>                         NA  >1.05  total
#>    beta_list_sensitive          1     /7
#> ────────────────────────────────────────────────────────────────────────────────

In this example, the printed output reports that some R-hats are problematic, so the model did not fully converge. This is because we used a very small number of iterations for speed; in practice, increase iter (and chains) to get reliable convergence.

Key components:

  • prob_public / prob_private: tibbles with id and a draws matrix-column, one row per respondent.
  • response_public / response_private: observed responses aligned to the model inputs.
  • response_majority: optional majority responses, if supplied in the data.
  • draws_summary: posterior::summarise_draws() output for all parameters.
  • rhat_summary: quick counts of R-hat problems per parameter family.
  • sim_public / sim_private: tibbles with id and a draws matrix-column containing simulated outcomes, handy for posterior predictive checks.

You can also inspect each element directly:

model_pets$prob_public
#> # A tibble: 500 × 2
#>    id     draws[,1]     [,2]     [,3]   [,4]   [,5]    [,6]   [,7]   [,8]   [,9]
#>    <chr>   <I<dbl>> <I<dbl>> <I<dbl>> <I<db> <I<db> <I<dbl> <I<db> <I<db> <I<db>
#>  1 LX0001    0.0959   0.102   0.146   0.211  0.144  0.206   0.163  0.164  0.0930
#>  2 LX0002    0.155    0.193   0.260   0.142  0.244  0.138   0.178  0.200  0.218 
#>  3 LX0003    0.0791   0.0866  0.0770  0.105  0.103  0.152   0.151  0.163  0.104 
#>  4 LX0004    0.247    0.105   0.114   0.0702 0.101  0.147   0.0750 0.169  0.235 
#>  5 LX0005    0.0817   0.100   0.0915  0.122  0.160  0.119   0.127  0.146  0.161 
#>  6 LX0006    0.0188   0.0181  0.00737 0.0628 0.0275 0.00970 0.0353 0.0503 0.0454
#>  7 LX0007    0.284    0.175   0.132   0.0882 0.0692 0.268   0.0973 0.136  0.107 
#>  8 LX0008    0.151    0.169   0.225   0.122  0.164  0.174   0.209  0.222  0.144 
#>  9 LX0009    0.0791   0.0866  0.0770  0.105  0.103  0.152   0.151  0.163  0.104 
#> 10 LX0010    0.241    0.0905  0.0965  0.0596 0.0639 0.185   0.0900 0.188  0.157 
#> # ℹ 490 more rows
#> # ℹ 1 more variable: draws[10:200] <I<dbl>>
model_pets$rhat_summary
#> # A tibble: 17 × 5
#>    array                        n  n_na  n_gt  n_ok
#>    <chr>                    <int> <int> <int> <int>
#>  1 beta_list_control            7     0     0     7
#>  2 beta_list_sensitive          7     0     1     6
#>  3 beta_public                  7     0     0     7
#>  4 control_logit              500     0     0   500
#>  5 intercept_list_control       1     0     0     1
#>  6 intercept_list_sensitive     1     0     0     1
#>  7 intercept_public             1     0     0     1
#>  8 lp__                         1     0     0     1
#>  9 private_sim                500     0     0   500
#> 10 prob_hid_neg               500     0     0   500
#> 11 prob_hid_pos               500     0     0   500
#> 12 prob_private               500     0     0   500
#> 13 prob_public                500     0     0   500
#> 14 public_in_private_logit    500     0     0   500
#> 15 public_logit               262     0     0   262
#> 16 public_sim                 262     0     0   262
#> 17 sensitive_logit            500     0     0   500

Predictions

lx_predict_for_cohorts() summarizes posterior draws (and majority answers if available). By default it aggregates over all respondents in the model:

all_pred <- lx_predict_for_cohorts(model_pets)
#> ℹ No weights provided. Using equal weights of 1.
all_pred
#> # A tibble: 4 × 5
#>   component   mean   lower  upper draws      
#>   <chr>      <dbl>   <dbl>  <dbl> <list>     
#> 1 public    0.158   0.115   0.209 <dbl [200]>
#> 2 private   0.253   0.120   0.411 <dbl [200]>
#> 3 delta     0.0957 -0.0446  0.271 <dbl [200]>
#> 4 majority  0.226  NA      NA     <dbl [0]>

For multiple cohorts, pass a cohort set:

cohort_set <- 
  example_srv_lx |>
  g6tr.cohorts::create_cohort_set(
    id_col = response_id,
    grp_cols = c(d_gender),
    weight_col = weight
  )

set_pred <- lx_predict_for_cohorts(model_pets, cohorts = cohort_set)
set_pred
#> Cohort Set
#> # A tibble: 3 × 7
#>   column     label              level      cohort       n weighted_n predictions
#>   <chr>      <chr>              <chr>      <list>   <int>      <dbl> <list>     
#> 1 population Overall population population <cohort>   500       500  <tibble>   
#> 2 d_gender   Gender             male       <cohort>   244       238. <tibble>   
#> 3 d_gender   Gender             female     <cohort>   256       262. <tibble>
set_pred$predictions[[1]]
#> # A tibble: 4 × 5
#>   component   mean   lower  upper draws      
#>   <chr>      <dbl>   <dbl>  <dbl> <list>     
#> 1 public    0.168   0.121   0.221 <dbl [200]>
#> 2 private   0.266   0.133   0.427 <dbl [200]>
#> 3 delta     0.0979 -0.0419  0.275 <dbl [200]>
#> 4 majority  0.231  NA      NA     <dbl [0]>

For a detailed guide to all cohorts options (including "predictors", explicit predictor subsets, and "population"), see 3_predictions.Rmd.

To visualize these summaries, use lx_strip_plot():

lx_strip_plot(model_pets)
#> ℹ No weights provided. Using equal weights of 1.

lx_strip_plot(model_pets, cohorts = cohort_set)

In these plots, the private distribution is noticeably wider than the public one. That is expected: public agreement is observed directly, while private agreement is inferred from indirect list responses, which adds uncertainty.

Fitting multiple experiments

There is no single-call helper for fitting multiple experiments yet, but it is easy to do by iterating over the parsed rows:

models <- parsed
models$model <- vector("list", nrow(models))

for (i in seq_len(nrow(models))) {
  cli::cli_progress_step("Fitting {.val {models$experiment[[i]]}}")
  models$model[[i]] <- lx_fit(
    models$data[[i]],
    iter = 1000,
    chains = 4,
    cores = 4
  )
  cli::cli_progress_done()
}