prepare_mxl_data: Prepare inputs for mixed logit estimation

View source: R/mxlogit_utils.R

prepare_mxl_dataR Documentation

Prepare inputs for mixed logit estimation

Description

Prepares and validates inputs for mixed logit estimation routine.

Usage

prepare_mxl_data(
  data,
  id_col,
  alt_col,
  choice_col,
  covariate_cols,
  random_var_cols,
  weights = NULL,
  outside_opt_label = NULL,
  include_outside_option = FALSE,
  rc_correlation = FALSE,
  weights_col = NULL,
  cluster_col = NULL
)

Arguments

data

Data frame containing choice data

id_col

Name of the column identifying choice situations (individuals)

alt_col

Name of the column identifying alternatives

choice_col

Name of the column indicating chosen alternative (1 = chosen, 0 = not chosen)

covariate_cols

Vector of names of columns to be used as covariates

random_var_cols

Vector of names of columns to be used as random variables

weights

Optional vector of weights for each choice situation. If NULL, equal weights are used. All weights must be finite and strictly positive.

outside_opt_label

Label for the outside option (if any). If NULL, no outside option is assumed.

include_outside_option

Logical indicating whether to include an outside option in the model.

rc_correlation

Logical indicating whether random coefficients are correlated. Default is FALSE.

weights_col

Optional name of a column in data holding a per-row weight (constant within each choice situation, finite and strictly positive). Mutually exclusive with weights.

cluster_col

Optional name of a column in data holding cluster labels for cluster-robust standard errors. Must be constant within each id_col; collapsed to one label per choice situation and returned as cluster.

Value

A choicer_data_mxl object (list) containing:

  • X: Fixed-coefficient design matrix (sum(M) x K_x).

  • W: Random-coefficient design matrix (sum(M) x K_w).

  • alt_idx: Integer vector of alternative indices.

  • choice_idx: Integer vector of chosen alternative indices.

  • M: Integer vector with number of alternatives per choice situation.

  • N: Number of choice situations.

  • weights: Vector of weights.

  • cluster: Vector of cluster labels (or NULL).

  • situation_ids: Choice-situation ids in prepared (sorted) order.

  • include_outside_option: Logical flag.

  • rc_correlation: Logical flag.

  • alt_mapping: data.table mapping alternatives to summary statistics.

  • dropped_cols: Names of columns dropped due to collinearity, if any.

  • data_spec: List with column-name metadata.

Examples

library(data.table)
set.seed(42)
N <- 50; J <- 3
dt <- data.table(id = rep(1:N, each = J), alt = rep(1:J, N))
dt[, `:=`(x1 = rnorm(.N), w1 = rnorm(.N), w2 = rnorm(.N))]
dt[, choice := 0L]
dt[, choice := sample(c(1L, rep(0L, J - 1))), by = id]
input <- prepare_mxl_data(dt, "id", "alt", "choice", "x1", c("w1", "w2"))
str(input$X)
str(input$W)

choicer documentation built on Sept. 5, 2026, 1:07 a.m.