Skip to contents

From raw survey to tidy data

List experiments rely on a carefully structured questionnaire: respondents are randomly assigned to treatment/control, asked how many statements they agree with (without revealing which ones), and later face direct public or majority questions about the sensitive item. Modeling the data requires respondent-level predictors along with standardized treatment assignments and response scales.

Raw survey exports often contain multiple list-experiment bundles in a single wide data frame with naming conventions such as {module}_{experiment}_{question_type}. Unfortunately, question texts, response codings, and factor encodings are rarely consistent across studies. The lx_parse_data() helper concentrates the tedious tasks of extracting the right columns and harmonizing their formats so downstream modeling code always receives predictable inputs.

A look at the example data

The package ships with example_srv_lx, a synthetic survey containing three bundles (pets, privacy, climate). Each respondent has an id, a treatment assignment, several demographic predictors, and repeated sets of private, public, and majority columns.

library(g6tr.lx)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

example_srv_lx |> glimpse()
#> Rows: 500
#> Columns: 15
#> $ response_id              <chr> "LX0001", "LX0002", "LX0003", "LX0004", "LX00…
#> $ d_gender                 <fct> female, female, male, female, female, female,…
#> $ d_age                    <fct> 18-30, 46-64, 46-64, 46-64, 46-64, 65+, 31-45…
#> $ d_hhincome               <fct> $25k-$50k, $50k-$100k, $25k-$50k, 100k+, $25k…
#> $ m2_list_treatment        <fct> trt, trt, trt, trt, ctrl, trt, ctrl, trt, trt…
#> $ weight                   <dbl> 1.3021318, 0.8817680, 0.8575626, 0.6146681, 0…
#> $ m2_list_pets_private     <int> 5, 4, 2, 1, 2, 1, 1, 2, 0, 2, 1, 3, 0, 3, 1, …
#> $ m3_list_pets_public      <fct> oppose, oppose, oppose, mixed, support, mixed…
#> $ m3_list_pets_majority    <fct> oppose, mixed, support, oppose, support, oppo…
#> $ m2_list_privacy_private  <int> 1, 3, 1, 3, 1, 3, 1, 2, 2, 3, 2, 2, 3, 2, 1, …
#> $ m3_list_privacy_public   <fct> mixed, oppose, oppose, support, oppose, mixed…
#> $ m3_list_privacy_majority <fct> mixed, mixed, oppose, mixed, oppose, mixed, s…
#> $ m2_list_climate_private  <int> 4, 1, 1, 3, 3, 2, 3, 2, 1, 3, 4, 2, 3, 2, 2, …
#> $ m3_list_climate_public   <fct> oppose, mixed, oppose, support, oppose, oppos…
#> $ m3_list_climate_majority <fct> support, oppose, mixed, support, oppose, oppo…

A few details to note:

  • m2_list_treatment stores treatment assignment using the ctrl/trt abbreviations that we want to remap to standardized control/treatment levels.
  • Private responses (e.g. m2_list_pets_private) are integer counts, but many surveys deliver them as factors whose labels must be coerced to numbers.
  • Public and majority columns in example_srv_lx happen to be factors with support/oppose/mixed labels, while other surveys might already use agree/disagree strings or something entirely different.
  • Predictors (here, d_gender, d_age, d_hhincome) pass through untouched: whatever preprocessing you want (e.g., collapsing levels, turning numerics into bins) must happen before parsing, because downstream models treat them as factors and internally apply dummy coding (n-1 binaries per n-level factor).

Parsing objectives

When we parse, we want to accomplish two things:

  1. Extract one tibble per experiment. Each tibble should contain only the respondents and columns relevant to that list-experiment bundle, plus the requested predictors.
  2. Standardize formats. Treatment must be a control/treatment factor, private counts must be numeric within the expected range (checked against n_insens), and public/majority outcomes must share the same agree/disagree/unsure vocabulary.

Most of the time the parser can convert messy survey encodings into the desired format by itself: private counts can be numeric or factors with numeric labels, and treatment/public/majority levels are recognized through built-in heuristics. If you want full control, pass explicit *_coding arguments to override those guesses; when neither the defaults nor your mappings fit the data, the parser fails fast so you can fix the issue before fitting a model.

Parsing all bundles at once

Because our survey follows a predictable naming scheme, we can let lx_parse_data() parse all bundles in one call using {exp} placeholders. The function returns a tibble with one row per experiment and a data list-column containing the parsed bundle.

parsed_lx_data <- lx_parse_data(
  data = example_srv_lx,
  n_insens = 4,
  id_col = response_id,
  weight_col = weight,
  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"),
  public_coding = c(agree = "support", disagree = "oppose", unsure = "mixed")
)
#> 
#> ── Experiment pets
#> • treatment column: m2_list_treatment
#> ├─ treatment <- "trt"
#> └─ control   <- "ctrl"
#> • private column: m2_list_pets_private
#> • public column: m3_list_pets_public
#> ├─ disagree <- "oppose"
#> ├─ unsure   <- "mixed"
#> └─ agree    <- "support"
#> • majority column: m3_list_pets_majority
#> ├─ disagree <- "oppose"
#> ├─ unsure   <- "mixed"
#> └─ agree    <- "support"
#> 
#> ── Experiment privacy
#> • treatment column: m2_list_treatment
#> ├─ treatment <- "trt"
#> └─ control   <- "ctrl"
#> • private column: m2_list_privacy_private
#> • public column: m3_list_privacy_public
#> ├─ unsure   <- "mixed"
#> ├─ disagree <- "oppose"
#> └─ agree    <- "support"
#> • majority column: m3_list_privacy_majority
#> ├─ unsure   <- "mixed"
#> ├─ disagree <- "oppose"
#> └─ agree    <- "support"
#> 
#> ── Experiment climate
#> • treatment column: m2_list_treatment
#> ├─ treatment <- "trt"
#> └─ control   <- "ctrl"
#> • private column: m2_list_climate_private
#> • public column: m3_list_climate_public
#> ├─ disagree <- "oppose"
#> ├─ unsure   <- "mixed"
#> └─ agree    <- "support"
#> • majority column: m3_list_climate_majority
#> ├─ agree    <- "support"
#> ├─ disagree <- "oppose"
#> └─ unsure   <- "mixed"
parsed_lx_data
#> # A tibble: 3 × 2
#>   experiment data               
#>   <chr>      <named list>       
#> 1 pets       <lx_data [500 × 7]>
#> 2 privacy    <lx_data [500 × 7]>
#> 3 climate    <lx_data [500 × 7]>

weight_col is optional. Weights do not affect model fitting, but setting them at parse time is useful for quick summaries on cohorts generated from model predictors.

Each data element is an object of class lx_data with harmonized columns. We can inspect one of them directly:

parsed_lx_data$data[[1]]
#> 
#> ── List Experiment Data ────────────────────────────────────────────────────────
#> Respondents: 500
#> Private complete cases: 500
#> Public complete cases: 500
#> Control statements: 4
#> Predictors: "d_gender", "d_age", "d_hhincome"
#> Metadata:
#> - 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.30  treatment       5 disagree disagree female              18-30 
#>  2 LX0002  0.882 treatment       4 disagree unsure   female              46-64 
#>  3 LX0003  0.858 treatment       2 disagree agree    male                46-64 
#>  4 LX0004  0.615 treatment       1 unsure   disagree female              46-64 
#>  5 LX0005  0.555 control         2 agree    agree    female              46-64 
#>  6 LX0006  0.789 treatment       1 unsure   disagree female              65+   
#>  7 LX0007  1.00  control         1 disagree disagree male                31-45 
#>  8 LX0008  0.825 treatment       2 unsure   disagree male                46-64 
#>  9 LX0009  0.937 treatment       0 disagree disagree male                46-64 
#> 10 LX0010  0.879 control         2 disagree disagree male                46-64 
#> # ℹ 490 more rows
#> # ℹ 1 more variable: predictors$d_hhincome <fct>
#> ────────────────────────────────────────────────────────────────────────────────

Notice that predictors are packed into a list-column, preserving any number of covariates while keeping the parsed tibble tidy.

Handling irregular column names

In the ideal case, all list-experiment columns follow one naming template where the same placeholder ({exp}) identifies the bundle across the private/public/majority questions. In real survey exports, that assumption can break.

No shared template

Sometimes the three parts of a bundle (private/public/majority) can’t be linked by a single template at all – names may use different conventions across question types, contain unrelated indices, or omit the experiment code in some places. In that case, the pairing can’t be inferred from templates alone: you need to determine the mapping (from the survey spec, labels, or a lookup table) and then either:

  1. Rename columns to a consistent template and parse everything at once, or
  2. Parse experiments one-by-one with explicit column names.

Here’s a toy example where public answers live in m3_opinion_* and majority answers live in m3_majority_* (so the match is effectively “by index”, not by {exp}):

example_flawed_srv_lx <-
  example_srv_lx |>
  rename(
    m3_opinion_2 = m3_list_pets_public,
    m3_opinion_5 = m3_list_privacy_public,
    m3_opinion_6 = m3_list_climate_public,

    m3_majority_2 = m3_list_pets_majority,
    m3_majority_5 = m3_list_privacy_majority,
    m3_majority_6 = m3_list_climate_majority
  )

If you already know the mapping, a straightforward approach is to rename the columns into a single template and run lx_parse_data() as usual. Alternatively, you can parse each experiment explicitly:

parsed_lx_data_pets <- lx_parse_data(
  data = example_flawed_srv_lx,
  n_insens = 4,
  id_col = response_id,
  treatment = m2_list_treatment,
  private = "m2_list_pets_private",
  public = "m3_opinion_2",
  majority = "m3_majority_2",
  predictors = starts_with("d_"),
  treatment_coding = c(control = "ctrl", treatment = "trt"),
  public_coding = c(agree = "support", disagree = "oppose", unsure = "mixed")
)

# then parse the other experiments in the same way and combine if needed

Extra placeholder tokens

Sometimes the experiment code is present, but some columns include an extra token that varies across experiments and is not part of the bundle identifier. For example:

example_excessive_srv_lx <-
  example_srv_lx |>
  rename(
    m2_list_funny_pets_private = m2_list_pets_private,
    m2_list_serious_privacy_private = m2_list_privacy_private,
    m2_list_serious_climate_private = m2_list_climate_private,
  )

Here the private columns include an extra segment between list and {exp}. You don’t need to rename anything if you can express that segment as a wildcard placeholder. For instance, treat it as {category} and use it only where it appears:

parsed_excessive_lx_data <- lx_parse_data(
  data = example_excessive_srv_lx,
  n_insens = 4,
  id_col = response_id,
  treatment = m2_list_treatment,
  private = "m2_list_{category}_{exp}_private",
  public = "m3_list_{exp}_public",
  majority = "m3_list_{exp}_majority",
  predictors = starts_with("d_"),
  treatment_coding = c(control = "ctrl", treatment = "trt"),
  public_coding = c(agree = "support", disagree = "oppose", unsure = "mixed")
)
parsed_excessive_lx_data
#> # A tibble: 3 × 3
#>   experiment category data               
#>   <chr>      <chr>    <named list>       
#> 1 pets       funny    <lx_data [500 × 7]>
#> 2 privacy    serious  <lx_data [500 × 7]>
#> 3 climate    serious  <lx_data [500 × 7]>

Optional metadata

lx_parse_data() already stores the parsed experiment code as experiment metadata on each lx_data object.

Attaching statement wording to each parsed lx_data object is optional, but it is handy metadata to keep alongside the experiment bundle. Metadata set on lx_data is also carried over automatically to the fitted lx_model.

Use lx_set_metadata() when you want to override experiment (for example, if parsed codes are not informative enough) and/or add optional statement wording. One convenient pattern is to define statements in a small lookup table, join by experiment, and then apply metadata row-wise:

statement_tbl <- tibble::tribble(
  ~experiment, ~statement,
  "pets", "Adopt a shelter pet this year",
  "privacy", "Data privacy protections should be stronger",
  "climate", "Climate policy should be prioritized even at economic cost"
)

parsed_lx_data <-
  parsed_lx_data |>
  dplyr::left_join(statement_tbl, by = "experiment") |>
  dplyr::rowwise() |>
  dplyr::mutate(data = list(lx_set_metadata(data, statement = statement))) |>
  dplyr::ungroup()

attr(parsed_lx_data$data[[1]], "experiment")
#> [1] "pets"
attr(parsed_lx_data$data[[1]], "statement")
#> [1] "Adopt a shelter pet this year"

Where to go next

The parsed bundles feed directly into lx_fit(), which fits the latent opinion model and produces posterior draws for each respondent’s public and private agreement probabilities. See the “Fitting List Experiment Models” vignette.