View source: R/nestlogit_utils.R
| prepare_nl_data | R Documentation |
Validates inputs, builds design matrices, and constructs nest structure
for nested logit estimation. Calls prepare_mnl_data internally
for base data preparation, then adds nest-specific fields.
prepare_nl_data(
data,
id_col,
alt_col,
choice_col,
covariate_cols,
nest_col,
weights = NULL,
outside_opt_label = NULL,
include_outside_option = FALSE,
weights_col = NULL,
cluster_col = NULL
)
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. |
nest_col |
Name of the column mapping each alternative to its nest. Every alternative must belong to exactly one nest. |
weights |
Optional vector of weights for each choice situation. If |
outside_opt_label |
Label for the outside option (if any). If |
include_outside_option |
Logical indicating whether to include an outside option in the model. |
weights_col |
Optional name of a column in |
cluster_col |
Optional name of a column in |
A choicer_data_nl object (list) containing:
All fields from prepare_mnl_data (X, alt_idx,
choice_idx, M, N, weights, cluster,
situation_ids, include_outside_option, alt_mapping,
dropped_cols).
nest_idx: Integer vector of length J mapping each alternative
(in alt_mapping row order) to its nest.
data_spec: List with column name metadata including nest_col.
library(data.table)
set.seed(42)
N <- 50; J <- 4
dt <- data.table(id = rep(1:N, each = J), alt = rep(1:J, N))
dt[, `:=`(x1 = rnorm(.N), x2 = rnorm(.N))]
dt[, nest := ifelse(alt <= 2, "A", "B")]
dt[, choice := 0L]
dt[, choice := sample(c(1L, rep(0L, J - 1))), by = id]
input <- prepare_nl_data(dt, "id", "alt", "choice", c("x1", "x2"), "nest")
input$nest_idx
input$alt_mapping
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.