| Type: | Package |
| Title: | Working with Choice Data |
| Version: | 0.2.0 |
| Description: | Offers a set of objects tailored to simplify working with choice data. It enables the computation of choice probabilities and the likelihood of various types of choice models based on given data. |
| License: | GPL (≥ 3) |
| Encoding: | UTF-8 |
| Language: | en-US |
| URL: | https://github.com/loelschlaeger/choicedata, https://loelschlaeger.de/choicedata/ |
| BugReports: | https://github.com/loelschlaeger/choicedata/issues |
| Suggests: | AER, mlogit, mvtnorm, testthat (≥ 3.0.0) |
| Config/testthat/edition: | 3 |
| Imports: | checkmate, cli, dplyr, Formula, optimizeR (≥ 1.2.1), oeli (≥ 0.7.8), Rdpack, Rcpp, rlang, tibble, tidyr, utils |
| LinkingTo: | oeli (≥ 0.7.8), Rcpp, RcppArmadillo |
| RdMacros: | Rdpack |
| LazyData: | true |
| LazyDataCompression: | xz |
| Depends: | R (≥ 4.1.0) |
| RoxygenNote: | 8.0.0 |
| NeedsCompilation: | yes |
| Packaged: | 2026-09-15 11:42:30 UTC; loelschlaeger |
| Author: | Lennart Oelschläger
|
| Maintainer: | Lennart Oelschläger <oelschlaeger.lennart@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-09-15 12:20:02 UTC |
choicedata: Working with Choice Data
Description
Offers a set of objects tailored to simplify working with choice data. It enables the computation of choice probabilities and the likelihood of various types of choice models based on given data.
Author(s)
Maintainer: Lennart Oelschläger oelschlaeger.lennart@gmail.com (ORCID)
Authors:
Lennart Oelschläger oelschlaeger.lennart@gmail.com (ORCID)
See Also
Useful links:
Report bugs at https://github.com/loelschlaeger/choicedata/issues
Define choice alternatives
Description
The choice_alternatives object defines the set of choice alternatives.
Usage
choice_alternatives(
J = length(alternatives),
alternatives = LETTERS[1:J],
base = NULL,
ordered = FALSE
)
## S3 method for class 'choice_alternatives'
print(x, ...)
Arguments
J |
[ |
alternatives |
[ |
base |
[ If |
ordered |
[ When Otherwise, they are sorted alphabetically. |
x |
[ |
... |
Currently not used. |
Value
An object of class choice_alternatives, i.e. a character vector of the
choice alternatives with attributes:
JThe number of choice alternatives.
baseThe name of the base alternative.
orderedDo the alternatives encode an inherent ordering?
Base alternative
The full set of coefficients for covariates that are constant across
alternatives (including alternative-specific constants) is not identified.
To achieve identifiability, the coefficient of alternative base
is fixed to zero. The other coefficients then have to be interpreted with
respect to base. The base alternative is marked with a * when
printing a choice_alternatives object.
Examples
### unordered choice alternatives: heating
choice_alternatives(
J = 3,
alternatives = c("gas", "electricity", "oil"),
base = "gas"
)
### ordered choice alternatives: opinion
choice_alternatives(
J = 4,
alternatives = c("very good", "good", "neither good nor bad", "bad"),
ordered = TRUE
)
Define choice covariates
Description
The choice_covariates object defines the choice model covariates.
-
generate_choice_covariates()samples covariates. -
covariate_names()gives the covariate names for givenchoice_effects. -
design_matrices()builds design matrices.
Usage
choice_covariates(
data_frame,
format = "wide",
column_decider = "deciderID",
column_occasion = NULL,
column_alternative = NULL,
column_ac_covariates = NULL,
column_as_covariates = NULL,
delimiter = "_",
cross_section = is.null(column_occasion)
)
generate_choice_covariates(
choice_effects = NULL,
choice_identifiers = generate_choice_identifiers(N = 100),
labels = if (is.null(choice_effects)) {
character()
} else {
covariate_names(choice_effects)
},
n = nrow(choice_identifiers),
marginals = list(),
correlation = diag(length(labels)),
verbose = FALSE,
delimiter = "_"
)
covariate_names(choice_effects)
design_matrices(
x,
choice_effects,
choice_identifiers = extract_choice_identifiers(x)
)
Arguments
data_frame |
[ |
format |
[ |
column_decider |
[ |
column_occasion |
[ |
column_alternative |
[ |
column_ac_covariates |
[ |
column_as_covariates |
[ |
delimiter |
[ |
cross_section |
[ |
choice_effects |
[ |
choice_identifiers |
[ |
labels |
[ |
n |
[ |
marginals |
[ Each list entry must be named according to a regressor label, and the following distributions are currently supported:
|
correlation |
[ |
verbose |
[ |
x |
A |
Value
choice_covariates() and generate_choice_covariates() return a
choice_covariates tibble with the identifier and covariate columns. The
column roles are stored in the attributes format, column_decider,
column_occasion, column_alternative, column_ac_covariates,
column_as_covariates, delimiter, and cross_section, analogous to
choice_data.
covariate_names() returns a character vector.
design_matrices() returns a list of class choice_design_matrices with
one numeric design matrix per choice occasion, see the section below. The
attributes Tp (the number of choice occasions per decider), alternatives,
availability (the indices of the available alternatives per occasion), and
choice_type describe the structure.
Design matrices
A covariate design matrix contains the choice covariates of a decider at a
choice occasion. It is of dimension J x P, where J is
the number of choice alternatives and P the number of effects.
Examples
### sample covariates from choice effects
choice_effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ price | income | comfort,
error_term = "probit",
random_effects = c(
"price" = "cn",
"income" = "cn"
)
),
choice_alternatives = choice_alternatives(J = 3)
)
(choice_covariates <- generate_choice_covariates(
choice_effects = choice_effects,
choice_identifiers = generate_choice_identifiers(N = 3, Tp = 2)
))
Define choice data
Description
The choice_data object defines the choice data, it is a combination of
choice_responses and choice_covariates.
Usage
choice_data(
data_frame,
format = "wide",
column_choice = "choice",
column_decider = "deciderID",
column_occasion = NULL,
column_alternative = NULL,
column_ac_covariates = NULL,
column_as_covariates = NULL,
delimiter = "_",
cross_section = is.null(column_occasion),
choice_type = c("unordered", "ordered", "ranked")
)
generate_choice_data(
choice_effects,
choice_identifiers = generate_choice_identifiers(N = 100),
choice_covariates = generate_choice_covariates(choice_effects, choice_identifiers),
choice_parameters = generate_choice_parameters(choice_effects),
choice_preferences = generate_choice_preferences(choice_effects, choice_parameters,
choice_identifiers),
column_choice = "choice",
choice_type = c("unordered", "ordered", "ranked")
)
long_to_wide(
data_frame,
column_ac_covariates = NULL,
column_as_covariates = NULL,
column_choice = "choice",
column_alternative = "alternative",
column_decider = "deciderID",
column_occasion = NULL,
alternatives = as.character(unique(data_frame[[column_alternative]])),
delimiter = "_",
choice_type = c("unordered", "ordered", "ranked")
)
wide_to_long(
data_frame,
column_ac_covariates = NULL,
column_choice = "choice",
column_alternative = "alternative",
alternatives = NULL,
delimiter = "_",
choice_type = c("unordered", "ordered", "ranked")
)
Arguments
data_frame |
[ |
format |
[ |
column_choice |
[ In long layout the same column is evaluated once per alternative: unordered
data use a binary indicator, An entirely missing response marks an occasion that is omitted from the
likelihood. Set to |
column_decider |
[ |
column_occasion |
[ |
column_alternative |
[ |
column_ac_covariates |
[ |
column_as_covariates |
[ |
delimiter |
[ |
cross_section |
[ |
choice_type |
[ |
choice_effects |
[ |
choice_identifiers |
[ |
choice_covariates |
[ |
choice_parameters |
[ |
choice_preferences |
[ |
alternatives |
[ |
Value
A choice_data tibble in the supplied format. It contains the identifier
columns, the response column(s), and the covariate columns of data_frame.
The column roles are stored as attributes, which the functions consuming
the object rely on:
formatEither
"wide"or"long".column_choiceThe name of the response column.
column_decider,column_occasionThe identifier columns.
column_alternativeThe alternative column (
format = "long").column_ac_covariates,column_as_covariatesThe names of the alternative-constant and alternative-specific covariates.
column_as_covariates_wideThe alternative-specific covariate columns in wide layout.
delimiter,cross_section,choice_typeThe corresponding input arguments.
Examples
### simulate data from a multinomial probit model
choice_effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ A | B,
error_term = "probit",
random_effects = c("A" = "cn")
),
choice_alternatives = choice_alternatives(J = 3)
)
generate_choice_data(choice_effects = choice_effects)
### transform from long to wide format
data("TravelMode", package = "AER")
TravelMode$choice <- TravelMode$choice == "yes"
long_to_wide(
data_frame = TravelMode,
column_alternative = "mode",
column_decider = "individual"
)
### transform from wide to long format
data("Train", package = "mlogit")
wide_to_long(
data_frame = Train
)
### individual choice sets and a missing response
partial_data <- data.frame(
deciderID = c(1, 1, 2),
alternative = c("A", "B", "B"),
choice = c(1L, 0L, NA),
cost = c(1.2, 1.5, 0.8)
)
choice_data(
data_frame = partial_data,
format = "long",
column_decider = "deciderID",
column_alternative = "alternative",
column_as_covariates = "cost"
)
Define choice model effects
Description
This function constructs an object of class choice_effects, which
defines the effects of a choice model.
Usage
choice_effects(
choice_formula,
choice_alternatives,
choice_data = NULL,
delimiter = "_"
)
## S3 method for class 'choice_effects'
print(x, ...)
Arguments
choice_formula |
[ |
choice_alternatives |
[ |
choice_data |
[ Required to resolve data-dependent elements in |
delimiter |
[ |
x |
[ |
... |
Currently not used. |
Value
A choice_effects object, which is a data.frame, where each row
is a model effect, and columns are
-
"effect_name", the name for the effect which is composed of covariate and alternative name, -
"generic_name", the generic effect name"beta_<effect number>", -
"covariate", the (transformed) covariate name connected to the effect, -
"alternative", the alternative name connected to the effect (only if the effect is alternative-specific), -
"as_covariate", indicator whether the covariate is alternative-specific, -
"as_effect", indicator whether the effect is alternative-specific, -
"mixing", a factor with levels in the order-
"cn"(correlated normal distribution), -
"cln"(positively signed correlated log-normal distribution), -
"cln-"(negatively signed correlated log-normal distribution), -
"n"(uncorrelated normal distribution), -
"ln"(positively signed uncorrelated log-normal distribution), -
"ln-"(negatively signed uncorrelated log-normal distribution),
indicating the type of random effect,
-
-
"latent_class", indicator whether the effect differs between latent classes.
For identification, the choice effects are ordered according to the following rules:
Non-random effects come before random effects.
Otherwise, the order is determined by occurrence in
formula.
It contains the arguments choice_formula, choice_alternatives, and
delimiter as attributes.
Examples
### construct choice effects
choice_effects(
choice_formula = choice_formula(
formula = choice ~ price | income | I(comfort == 1),
error_term = "probit",
random_effects = c(
"price" = "cn",
"income" = "cn"
)
),
choice_alternatives = choice_alternatives(J = 3)
)
Define choice model formula
Description
The choice_formula object defines the choice model equation.
Usage
choice_formula(
formula,
error_term = "probit",
random_effects = character(),
latent_class_effects = character()
)
## S3 method for class 'choice_formula'
print(x, ...)
Arguments
formula |
[ |
error_term |
[
|
random_effects |
[ |
latent_class_effects |
[ |
x |
[ |
... |
Currently not used. |
Value
An object of class choice_formula, which is a list of the elements:
formulaThe model formula.
error_termThe name of the model's error term specification.
choiceThe name of the response variable.
covariate_typesThe (up to) three different types of covariates.
ASCDoes the model have ASCs?
random_effectsThe names of covariates with random effects.
latent_class_effectsThe names of covariates with latent class effects.
xlevelsThe factor levels of the covariates, added once the formula has been resolved with data in
choice_effects.
Specifying the model formula
The structure of formula is choice ~ A | B | C, i.e., a standard
formula object but with three parts on the right-hand
side, separated by |, where
-
choiceis the name of the discrete response variable, -
Aare names of alternative-specific covariates with a coefficient that is constant across alternatives, -
Bare names of covariates that are constant across alternatives, and
Care names of alternative-specific covariates with alternative-specific coefficients.
The following rules apply:
By default, intercepts (referred to as alternative-specific constants, ASCs) are added to the model. They can be removed by adding
+ 0in the second part, e.g.,choice ~ A | B + 0 | C. To not include any covariates of the second type but to estimate ASCs, add1in the second part, e.g.,choice ~ A | 1 | C. The expressionchoice ~ A | 0 | Cis interpreted as no covariates of the second type and no ASCs.To not include covariates of any type, add
0in the respective part, e.g.,choice ~ 0 | B | C.Some parts of the formula can be omitted when there is no ambiguity. For example,
choice ~ Ais equivalent tochoice ~ A | 1 | 0.Multiple covariates in one part are separated by a
+sign, e.g.,choice ~ A1 + A2.Arithmetic transformations of covariates in all three parts of the right-hand side are possible via the function
I(), e.g.,choice ~ I(A1^2 + A2 * 2). In this case, a random effect can be defined for the transformed covariate, e.g.,random_effects = c("I(A1^2 + A2 * 2)" = "cn").Ordered choice models have a single utility per choice occasion. Their covariates must be placed in the first part and ASCs must be removed, e.g.,
choice ~ age + income | 0.
Specifying random effects
Specify random effects as "<covariate>" = "<distribution>". Each covariate
must appear explicitly on the right-hand side of formula; use "ASC" for
alternative-specific constants.
Available distributions are:
-
"cn": correlated normal -
"n": uncorrelated normal -
"cln": positively signed correlated log-normal -
"ln": positively signed uncorrelated log-normal -
"cln-": negatively signed correlated log-normal -
"ln-": negatively signed uncorrelated log-normal
Specifying latent class effects
The covariates in latent_class_effects have effects that differ between
the latent classes of a mixture model; use "ASC" for alternative-specific
constants. A random effect named here has a class-specific mean and
covariance, any other effect a class-specific coefficient. Effects that
are not named are the same in every class, and random effects with and
without latent class effects are uncorrelated. A model with more than one
latent class needs at least one latent class effect.
Examples
### specify a choice formula
choice_formula(
formula = choice ~ I(A^2 + 1) | B | I(log(C)),
error_term = "probit",
random_effects = c("I(A^2+1)" = "cn", "B" = "cn"),
latent_class_effects = "B"
)
Define choice identifiers
Description
The choice_identifiers object defines identifiers for the deciders and
choice occasions.
-
generate_choice_identifiers()generates identifiers. -
extract_choice_identifiers()extracts choice identifiers.
Usage
choice_identifiers(
data_frame,
format = "wide",
column_decider = "deciderID",
column_occasion = "occasionID",
cross_section = is.null(column_occasion)
)
generate_choice_identifiers(
N = length(Tp),
Tp = 1,
column_decider = "deciderID",
column_occasion = "occasionID"
)
extract_choice_identifiers(
x,
format = attr(x, "format"),
column_decider = attr(x, "column_decider"),
column_occasion = attr(x, "column_occasion"),
cross_section = attr(x, "cross_section")
)
Arguments
data_frame |
[ |
format |
[ In the long case, unique combinations of |
column_decider |
[ |
column_occasion |
[ |
cross_section |
[ |
N |
[ |
Tp |
[ Can also be of length |
x |
A |
Value
An object of class choice_identifiers, which is a tibble with columns:
-
column_decidercontains the decider identifiers, -
column_occasioncontains the choice occasion identifiers (only ifcolumn_occasionis notNULLandcross_section = FALSE).
The column names are stored in the attributes column_decider and
column_occasion, the attribute cross_section records the data type.
Examples
### panel case
generate_choice_identifiers(N = 2, Tp = 2)
### cross-sectional case
generate_choice_identifiers(N = 5, column_occasion = NULL)
### read choice identifiers
data("TravelMode", package = "AER")
choice_identifiers(
data_frame = TravelMode,
format = "long",
column_decider = "individual",
column_occasion = NULL,
cross_section = TRUE
)
Define and compute choice likelihood
Description
These functions prepare and evaluate the likelihood contribution of observed choices for a given choice model.
-
choice_likelihood()pre-computes the design matrices and choice indices implied bychoice_dataandchoice_effects. The returned object stores these quantities so that repeated likelihood evaluations during maximum likelihood estimation avoid redundant work. -
compute_choice_likelihood()evaluates the (log-)likelihood for givenchoice_parametersand a pre-computedchoice_likelihoodobject.
Usage
choice_likelihood(
choice_data,
choice_effects,
choice_identifiers = extract_choice_identifiers(choice_data),
input_checks = TRUE,
...
)
compute_choice_likelihood(
choice_parameters,
choice_likelihood,
logarithm = TRUE,
negative = FALSE,
aggregate = c("total", "decider", "occasion"),
...
)
Arguments
choice_data |
[ |
choice_effects |
[ |
choice_identifiers |
[ |
input_checks |
[ |
... |
Additional arguments for the probability computation:
|
choice_parameters |
[ A numeric vector in optimization space is also accepted and converted with
A list of either representation is evaluated as a batch of parameter draws. |
choice_likelihood |
[ |
logarithm |
[ |
negative |
[ |
aggregate |
[
|
Value
choice_likelihood() returns an object of class choice_likelihood, which
is a list containing the design matrices, choice indices, and identifiers.
compute_choice_likelihood() returns a numeric scalar for
aggregate = "total" and a named numeric vector otherwise.
Examples
### compute choice likelihood
data("Train", package = "mlogit")
choice_effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ price | time,
error_term = "probit"
),
choice_alternatives = choice_alternatives(
J = 2,
alternatives = c("A", "B")
)
)
choice_data <- choice_data(
data_frame = Train,
format = "wide",
column_choice = "choice",
column_decider = "id",
column_occasion = "choiceid"
)
likelihood <- choice_likelihood(
choice_data = choice_data,
choice_effects = choice_effects
)
choice_parameters <- generate_choice_parameters(
choice_effects = choice_effects
)
compute_choice_likelihood(
choice_parameters = choice_parameters,
choice_likelihood = likelihood,
logarithm = TRUE
)
Define choice model parameters
Description
These functions construct, validate, and transform an object of class
choice_parameters, which defines the parameters of a choice model.
-
choice_parameters()constructs achoice_parametersobject. -
generate_choice_parameters()samples parameters at random, see the details on sampling missing choice model parameters. -
validate_choice_parameters()checks model-specific dimensions. -
switch_parameter_space()transforms achoice_parametersobject between the interpretation and optimization space, see the details on the parameter spaces.
Usage
choice_parameters(
beta = NULL,
Omega = NULL,
Sigma = NULL,
gamma = NULL,
weights = NULL
)
generate_choice_parameters(
choice_effects,
fixed_parameters = choice_parameters(),
C = 1L
)
validate_choice_parameters(
choice_parameters,
choice_effects,
allow_missing = FALSE
)
switch_parameter_space(choice_parameters, choice_effects)
Arguments
beta |
[ For a latent class model, a list of one coefficient vector per class.
Only the effects named in |
Omega |
[ Not used when In a latent class model, a list of one covariance matrix per class. Only the block of the random effects with latent class effects may differ between the classes, and it is uncorrelated with the other random effects. Covariances involving uncorrelated random effects are fixed to zero. |
Sigma |
[ For unordered alternatives it is the covariance matrix for the Gaussian error
term In ordered models it reduces to a single variance term. |
gamma |
[ The first element must equal zero for identification. |
weights |
[ |
choice_effects |
[ |
fixed_parameters |
[ |
C |
[ |
choice_parameters |
[ |
allow_missing |
[ |
Value
choice_parameters(), generate_choice_parameters(), and
validate_choice_parameters() return a choice_parameters list with the
elements:
betaThe coefficient vector (if any).
OmegaThe random-effect covariance matrix on the underlying normal scale (if any).
SigmaThe error term covariance matrix (or variance in ordered models).
gammaThreshold parameters for ordered models (if any).
weightsThe latent class weights (if any).
switch_parameter_space() returns a named numeric vector when given a
choice_parameters object and a choice_parameters object when given a
numeric optimization vector.
Sampling missing choice model parameters
generate_choice_parameters() completes required components that are absent
from fixed_parameters.
Missing components are generated as follows:
betaDrawn from a multivariate normal distribution with zero mean and covariance matrix
10 * diag(P), independently for each class for the effects with latent classes and once for the others. A namedbetawith fewer thanPentries fixes the named effects and draws the others.OmegaDrawn from an Inverse-Wishart distribution with identity scale matrix and degrees of freedom equal to the dimension plus two, independently for each class for the block of the random effects with latent classes and once for the block of the others. Covariances involving uncorrelated random effects are then set to zero.
SigmaFor unordered probit models, the lower right block is drawn from an Inverse-Wishart distribution with
J + 1degrees of freedom and identity scale matrix. The first row and column are fixed to zero and the matrix is scaled so that element(2, 2)equals one. For ordered probit models,Sigmais set to one; logit models do not useSigma.gammaFor ordered models with two categories, set to zero. Otherwise, positive increments are drawn as
exp(z), where the elements ofzare independent standard normal draws, and cumulatively added to the first threshold zero. Unordered models do not usegamma.weightsSet to equal class probabilities
1 / C.
Parameter spaces
The switch_parameter_space() function transforms a choice_parameters
object between the interpretation and optimization space.
The interpretation space is a
listof (not necessarily identified) parameters that can be interpreted.The optimization space is a
numericvector of identified parameters that can be optimized:-
betais not transformed -
Omegais represented by its vectorized unique Cholesky factor; elements involving uncorrelated random effects are omitted for unordered probit models,
Sigmais represented through utility differences relative to the first alternative, with the first variance fixed to one, and transformed to a vectorized unique Cholesky factorfor ordered probit models, the positive scalar
Sigmais log-transformedthe first ordered threshold is fixed to zero and omitted; logarithms of the remaining positive threshold increments are used
in a latent class model, the coefficients and Cholesky elements of the effects with latent classes are concatenated in class order and followed by those of the other effects, which appear once;
C - 1log weight ratios use the first class as reference
-
Examples
### generate choice parameters at random
J <- 3
choice_effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x | y, error_term = "probit",
random_effects = c("x" = "cn")
),
choice_alternatives = choice_alternatives(J = J)
)
(parameters <- generate_choice_parameters(
choice_effects = choice_effects,
fixed_parameters = choice_parameters(
Sigma = diag(c(0, rep(1, J - 1))) # scale and level normalization
)
))
### switch between interpretation and optimization spaces
(optimization_parameters <- switch_parameter_space(
choice_parameters = parameters,
choice_effects = choice_effects
))
switch_parameter_space(
choice_parameters = optimization_parameters,
choice_effects = choice_effects
)
Define choice preferences
Description
The choice_preferences object defines the deciders' preferences in the
choice model.
-
choice_preferences()constructs achoice_preferencesobject. -
generate_choice_preferences()samples choice preferences at random.
Usage
choice_preferences(data_frame, column_decider = "deciderID")
generate_choice_preferences(
choice_effects,
choice_parameters = generate_choice_parameters(choice_effects),
choice_identifiers = generate_choice_identifiers(N = 100)
)
Arguments
data_frame |
[ |
column_decider |
[ |
choice_effects |
[ |
choice_parameters |
[ |
choice_identifiers |
[ |
Value
An object of class choice_preferences, which is a tibble with the
deciders' preferences. The column names are the names of the effects in the
choice model. The first column contains the decider identifiers, its name is
stored in the attribute column_decider.
Examples
### generate choice preferences from choice parameters and effects
set.seed(1)
choice_effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ price | income | comfort,
error_term = "probit",
random_effects = c(
"price" = "cn",
"income" = "cn"
),
latent_class_effects = "price"
),
choice_alternatives = choice_alternatives(J = 3)
)
choice_parameters <- generate_choice_parameters(
choice_effects = choice_effects, C = 2
)
(choice_preferences <- generate_choice_preferences(
choice_parameters = choice_parameters,
choice_effects = choice_effects,
choice_identifiers = generate_choice_identifiers(N = 4)
))
Define choice probabilities
Description
The choice_probabilities object defines the choice probabilities.
-
compute_choice_probabilities()calculates the choice probabilities based on the choice parameters and the choice data.
Usage
choice_probabilities(
data_frame,
choice_only = TRUE,
column_decider = "deciderID",
column_occasion = NULL,
cross_section = is.null(column_occasion),
column_probabilities = NULL,
logarithm = FALSE,
aggregate = c("occasion", "decider")
)
compute_choice_probabilities(
choice_parameters,
choice_data,
choice_effects,
choice_only = TRUE,
input_checks = TRUE,
aggregate = c("occasion", "decider"),
logarithm = FALSE,
...
)
Arguments
data_frame |
[ |
choice_only |
[ |
column_decider |
[ |
column_occasion |
[ |
cross_section |
[ |
column_probabilities |
[ If |
logarithm |
[ |
aggregate |
[ |
choice_parameters |
[ |
choice_data |
[ |
choice_effects |
[ |
input_checks |
[ |
... |
Additional arguments for the probability computation:
|
Value
A choice_probabilities tibble with the identifier columns followed by the
probability column(s). If choice_only = TRUE, there is a single column
choice_probability (or log_choice_probability if logarithm = TRUE).
Otherwise, there is one column per choice alternative. The attributes
column_decider, column_occasion, cross_section,
column_probabilities, choice_only, logarithm, and aggregate store
the column roles and the probability type.
If choice_only = FALSE and aggregate = "decider", the tibble instead has
one row per possible outcome sequence and decider, with the sequence in the
list column outcome.
Examples
### multinomial logit
set.seed(1)
effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x + z | 0,
error_term = "logit"
),
choice_alternatives = choice_alternatives(J = 2)
)
parameters <- choice_parameters(beta = c(0.2, -0.1))
simulated_data <- generate_choice_data(
choice_effects = effects,
choice_identifiers = generate_choice_identifiers(N = 1L),
choice_parameters = parameters
)
compute_choice_probabilities(
choice_parameters = parameters,
choice_data = simulated_data,
choice_effects = effects
)
### multinomial probit
set.seed(1)
effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x + z | 0,
error_term = "probit"
),
choice_alternatives = choice_alternatives(J = 2)
)
parameters <- choice_parameters(
beta = c(0.2, -0.1),
Sigma = diag(c(0, 1))
)
simulated_data <- generate_choice_data(
choice_effects = effects,
choice_identifiers = generate_choice_identifiers(N = 1L),
choice_parameters = parameters
)
compute_choice_probabilities(
choice_parameters = parameters,
choice_data = simulated_data,
choice_effects = effects
)
### ordered logit
set.seed(1)
effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x + z | 0,
error_term = "logit"
),
choice_alternatives = choice_alternatives(
J = 3,
ordered = TRUE
)
)
parameters <- choice_parameters(
beta = c(0.2, -0.1),
gamma = c(0, 1)
)
simulated_data <- generate_choice_data(
choice_effects = effects,
choice_identifiers = generate_choice_identifiers(N = 1L),
choice_parameters = parameters,
choice_type = "ordered"
)
compute_choice_probabilities(
choice_parameters = parameters,
choice_data = simulated_data,
choice_effects = effects
)
### ordered probit
set.seed(1)
effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x + z | 0,
error_term = "probit"
),
choice_alternatives = choice_alternatives(
J = 3,
ordered = TRUE
)
)
parameters <- choice_parameters(
beta = c(0.2, -0.1),
Sigma = 1,
gamma = c(0, 1)
)
simulated_data <- generate_choice_data(
choice_effects = effects,
choice_identifiers = generate_choice_identifiers(N = 1L),
choice_parameters = parameters,
choice_type = "ordered"
)
compute_choice_probabilities(
choice_parameters = parameters,
choice_data = simulated_data,
choice_effects = effects
)
### ranked logit
set.seed(1)
effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x + z | 0,
error_term = "logit"
),
choice_alternatives = choice_alternatives(J = 2)
)
parameters <- choice_parameters(beta = c(0.2, -0.1))
simulated_data <- generate_choice_data(
choice_effects = effects,
choice_identifiers = generate_choice_identifiers(N = 1L),
choice_parameters = parameters,
choice_type = "ranked"
)
compute_choice_probabilities(
choice_parameters = parameters,
choice_data = simulated_data,
choice_effects = effects
)
### ranked probit
set.seed(1)
effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x + z | 0,
error_term = "probit"
),
choice_alternatives = choice_alternatives(J = 2)
)
parameters <- choice_parameters(
beta = c(0.2, -0.1),
Sigma = diag(c(0, 1))
)
simulated_data <- generate_choice_data(
choice_effects = effects,
choice_identifiers = generate_choice_identifiers(N = 1L),
choice_parameters = parameters,
choice_type = "ranked"
)
compute_choice_probabilities(
choice_parameters = parameters,
choice_data = simulated_data,
choice_effects = effects
)
### mixed logit
set.seed(1)
effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x + z | 0,
error_term = "logit",
random_effects = c(
x = "cn",
z = "cn"
)
),
choice_alternatives = choice_alternatives(J = 2)
)
parameters <- choice_parameters(
beta = c(0.2, -0.1),
Omega = matrix(c(0.1, 0.02, 0.02, 0.1), nrow = 2)
)
simulated_data <- generate_choice_data(
choice_effects = effects,
choice_identifiers = generate_choice_identifiers(N = 1L),
choice_parameters = parameters
)
compute_choice_probabilities(
choice_parameters = parameters,
choice_data = simulated_data,
choice_effects = effects
)
### mixed probit
set.seed(1)
effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x + z | 0,
error_term = "probit",
random_effects = c(
x = "cn",
z = "cn"
)
),
choice_alternatives = choice_alternatives(J = 2)
)
parameters <- choice_parameters(
beta = c(0.2, -0.1),
Omega = matrix(c(0.1, 0.02, 0.02, 0.1), nrow = 2),
Sigma = diag(c(0, 1))
)
simulated_data <- generate_choice_data(
choice_effects = effects,
choice_identifiers = generate_choice_identifiers(N = 1L),
choice_parameters = parameters
)
compute_choice_probabilities(
choice_parameters = parameters,
choice_data = simulated_data,
choice_effects = effects
)
### panel logit
set.seed(1)
effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x + z | 0,
error_term = "logit",
random_effects = c(
x = "cn",
z = "cn"
)
),
choice_alternatives = choice_alternatives(J = 2)
)
parameters <- choice_parameters(
beta = c(0.2, -0.1),
Omega = matrix(c(0.1, 0.02, 0.02, 0.1), nrow = 2)
)
simulated_data <- generate_choice_data(
choice_effects = effects,
choice_identifiers = generate_choice_identifiers(
N = 1L,
Tp = 2L
),
choice_parameters = parameters
)
compute_choice_probabilities(
choice_parameters = parameters,
choice_data = simulated_data,
choice_effects = effects
)
### panel probit
set.seed(1)
effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x + z | 0,
error_term = "probit",
random_effects = c(
x = "cn",
z = "cn"
)
),
choice_alternatives = choice_alternatives(J = 2)
)
parameters <- choice_parameters(
beta = c(0.2, -0.1),
Omega = matrix(c(0.1, 0.02, 0.02, 0.1), nrow = 2),
Sigma = diag(c(0, 1))
)
simulated_data <- generate_choice_data(
choice_effects = effects,
choice_identifiers = generate_choice_identifiers(
N = 1L,
Tp = 2L
),
choice_parameters = parameters
)
compute_choice_probabilities(
choice_parameters = parameters,
choice_data = simulated_data,
choice_effects = effects,
aggregate = "decider",
cml = "ap"
)
### latent class logit
set.seed(1)
effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x + z | 0,
error_term = "logit",
latent_class_effects = c("x", "z")
),
choice_alternatives = choice_alternatives(J = 2)
)
parameters <- choice_parameters(
beta = list(c(0.2, -0.1), c(-0.2, 0.1)),
weights = c(0.5, 0.5)
)
simulated_data <- generate_choice_data(
choice_effects = effects,
choice_identifiers = generate_choice_identifiers(N = 1L),
choice_parameters = parameters
)
compute_choice_probabilities(
choice_parameters = parameters,
choice_data = simulated_data,
choice_effects = effects
)
### latent class probit
set.seed(1)
effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ x + z | 0,
error_term = "probit",
latent_class_effects = c("x", "z")
),
choice_alternatives = choice_alternatives(J = 2)
)
parameters <- choice_parameters(
beta = list(c(0.2, -0.1), c(-0.2, 0.1)),
Sigma = diag(c(0, 1)),
weights = c(0.5, 0.5)
)
simulated_data <- generate_choice_data(
choice_effects = effects,
choice_identifiers = generate_choice_identifiers(N = 1L),
choice_parameters = parameters
)
compute_choice_probabilities(
choice_parameters = parameters,
choice_data = simulated_data,
choice_effects = effects
)
Define choice response
Description
The choice_responses object defines the observed choice responses.
-
generate_choice_responses()simulates choices
Usage
choice_responses(
data_frame,
column_choice = "choice",
column_decider = "deciderID",
column_occasion = NULL,
cross_section = is.null(column_occasion)
)
generate_choice_responses(
choice_effects,
choice_covariates = generate_choice_covariates(choice_effects = choice_effects),
choice_parameters = generate_choice_parameters(choice_effects = choice_effects),
choice_identifiers = extract_choice_identifiers(choice_covariates),
choice_preferences = generate_choice_preferences(choice_parameters = choice_parameters,
choice_effects = choice_effects, choice_identifiers = choice_identifiers),
column_choice = "choice",
choice_type = c("unordered", "ordered", "ranked")
)
Arguments
data_frame |
[ |
column_choice |
[ |
column_decider |
[ |
column_occasion |
[ |
cross_section |
[ |
choice_effects |
[ |
choice_covariates |
[ |
choice_parameters |
[ |
choice_identifiers |
[ |
choice_preferences |
[ |
choice_type |
[ |
Value
A choice_responses tibble with the identifier columns followed by the
response column(s). The attributes column_choice, column_decider,
column_occasion, cross_section, and column_response_columns (all
non-identifier columns, e.g., the ranking columns for ranked responses)
store the column roles.
Examples
### generate choice responses from choice effects
choice_effects <- choice_effects(
choice_formula = choice_formula(
formula = choice ~ price | time,
error_term = "probit"
),
choice_alternatives = choice_alternatives(J = 5)
)
(generate_choice_responses(
choice_effects = choice_effects,
choice_type = "ranked"
))
Count model effects
Description
compute_P() returns the total number of effects in a choice model.
Usage
compute_P(choice_effects)
Arguments
choice_effects |
[ |
Value
An integer with the number of model effects.
Unique decider identifiers in cross-sectional case
Description
This helper function makes unique decider identifiers for a given combination of decider and occasion identifiers.
Usage
decider_identifiers_to_cross_section(
decider_identifiers,
occasion_identifiers,
delimiter = "."
)
Arguments
decider_identifiers, occasion_identifiers |
[ |
Value
An atomic vector of unique identifiers.
Expand Tp
Description
This helper function expands the number of choice occasions Tp to a
vector of length N.
Usage
expand_Tp(N = length(Tp), Tp = 1)
Arguments
N |
[ |
Tp |
[ Can also be of length |
Value
An integer vector of length N.
Get decider identifiers
Description
This helper function extracts the (unique) decider identifiers from a
choice_identifiers object.
Usage
get_decider_identifiers(choice_identifiers)
Arguments
choice_identifiers |
[ |
Value
An atomic vector of decider identifiers.
Get identifier position
Description
This helper function gets a position based on a decider and a choice occasion number.
Usage
get_position_from_identifier(
N = length(Tp),
Tp = 1,
decider_number,
occasion_number
)
Arguments
N |
[ |
Tp |
[ Can also be of length |
decider_number |
[ |
occasion_number |
[ |
Value
An integer position.
Berserk Choices in a Lichess Arena Tournament
Description
Revealed binary Berserk choices made by 5,852 players in the Lichess Yearly Rapid Arena held on April 16, 2026. The chess tournament used a 10-minute clock and lasted eight hours. Going Berserk at the beginning of a game reduced a player's clock to five minutes. In return, a win earned one extra tournament point. A player is considered to have been on a streak when they entered the game after at least two consecutive wins. While on a streak, a win was worth four instead of two points and a draw two instead of one. A Berserk win on a streak was therefore worth five points. A draw or loss ends the streak.
This data can be used to model the risky choice to go Berserk based on playing color, player rating, rating difference to the opponent, remaining tournament time, and risk to lose their winning streak.
Usage
lichess_berserk_choice
Format
A tibble with 37,416 rows and 8 columns:
- deciderID [
character] The player's Lichess username.
- occasionID [
integer] The player's games in chronological order, numbered from 1.
- berserk [
logical] Whether the player chose to go Berserk.
- white [
logical] Whether the player had the white pieces.
- rating [
integer] The player's Rapid rating at the beginning of the game.
- ratingDifference [
integer] The player's rating minus the opponent's rating.
- minutesRemaining [
numeric] The scheduled tournament time remaining, in minutes, when the game was created.
- streak [
logical] Whether the player was on a double-point win streak at the beginning of the game.
Source
Derived from the public game export, results, and tournament metadata for the Lichess Yearly Rapid Arena using the Lichess Arena API. The streak and Berserk rules are described in the Arena tournament FAQ. Lichess database exports are released under the CC0 license.
Read Tp
Description
This helper function reads the number of choice occasions Tp from a
choice_identifiers object.
Usage
read_Tp(choice_identifiers)
Arguments
choice_identifiers |
[ |
Value
An integer vector of length N, where N is the
number of deciders.
Split choice data into a train and a test subset
Description
This function splits choice data by deciders or by choice occasions, for example to fit a model on the train subset and to evaluate its predictions on the test subset.
Usage
train_test(
data_frame,
test_proportion = NULL,
test_number = NULL,
by = "decider",
random = FALSE,
column_decider = "deciderID",
column_occasion = NULL
)
Arguments
data_frame |
[ |
test_proportion |
[ |
test_number |
[ |
by |
[ |
random |
[ |
column_decider |
[ |
column_occasion |
[ |
Details
Exactly one of test_proportion and test_number sets the size of the test
subset. Splitting by occasions keeps every decider in both subsets and
applies the size per decider, which requires panel data.
Value
A list of two subsets of data_frame, named train and test.
Examples
data("Train", package = "mlogit")
### 20% of the deciders in the test subset
parts <- train_test(Train, test_proportion = 0.2, column_decider = "id")
lengths(lapply(parts, function(part) unique(part$id)))
### the last choice occasion of every decider in the test subset
parts <- train_test(
Train, test_number = 1, by = "occasion",
column_decider = "id", column_occasion = "choiceid"
)
nrow(parts$test)
Dairy-Farm Water Conservation Choices
Description
Stated panel choices by 98 dairy farmers in Mejia, Ecuador. Each farmer completed four choice tasks with two conservation plans and a status quo. The data have 1176 rows in long format.
This data can be used to model the choice between two water-conservation plans and the status quo based on irrigation, manure and waste management, training, cost-share payment, farm size, milk production, and cattle density.
Usage
water_conservation_choice
Format
A tibble with 1176 rows and 12 columns:
- farmer [
integer] The farmer identifier.
- occasion [
integer] The choice occasion from 1 to 4.
- alternative [
character] Plan 1, plan 2, or the status quo.
- choice [
integer] Whether the alternative was chosen.
- irrigation [
factor] No new system, micro-sprinklers, or solid rain.
- manure [
factor] No new practice, composting, or dispersion.
- waste [
factor] No new practice, a collection center, or a municipal container.
- training [
logical] Whether training for water conflict resolution and cooperation is offered.
- payment [
numeric] The cost-share payment in US dollars per hectare.
- farm_size [
numeric] The farm size in hectares.
- milk_production [
numeric] The daily milk production in liters.
- cattle_density [
numeric] The number of cattle per hectare.
Source
Adapted from the Mendeley Data source doi:10.17632/ncj6ws6hbj.1. The source data are licensed under CC BY 4.0.
References
Ortiz CA, Avila-Santamaría JJ, Martinez-Cruz AL (2023). “Dairy farmers' willingness to adopt cleaner production practices for water conservation: A discrete choice experiment in Mejia, Ecuador.” Agricultural Water Management, 278, 108168. doi:10.1016/j.agwat.2023.108168.
Choices for a Proposed Wind-Power Project
Description
Stated panel choices by 308 residents for a proposed wind-power project near Setskog, Norway. Each respondent completed six choice tasks. The alternatives are the status quo and two project plans. Compensation values were converted to Euro at an exchange rate of 10.8770 Norwegian kroner = 1 Euro.
This data can be used to model the choice between two wind-power project plans and the status quo based on the number and height of turbines, power-line placement, compensation, and collective psychological ownership.
Usage
wind_power_choice
Format
A tibble with 1848 rows and 16 columns:
- respondent [
integer] The respondent identifier.
- occasion [
integer] The choice occasion from 1 to 6.
- choice [
character] The chosen alternative from 1 to 3.
- turbines_1–turbines_3 [
integer] The number of turbines for each alternative.
- height_1–height_3 [
integer] The turbine height in meters for each alternative.
- powerline_1–powerline_3 [
factor] The power-line route and placement: none, overhead or underground throughout, or mixed between forests and residential areas.
- compensation_1–compensation_3 [
numeric] The annual reduction in municipal taxes offered as compensation, in euros.
- psychological_ownership [
numeric] A respondent-specific, model-estimated latent score for collective psychological ownership of the natural area affected by the proposed wind farm. It was constructed from three seven-point Likert items asking whether the area is "ours" and belongs collectively to residents. The construct was normalized to mean zero and standard deviation one in the study: positive values indicate stronger and negative values weaker feelings of shared ownership relative to the sample average.
Source
Adapted from the Mendeley Data source doi:10.17632/3pdx4p3s9g.1. The source data are licensed under CC BY 4.0.
References
Dugstad A, Grimsrud K, Kipperberg G, Lindhjem H, Navrud S (2023). “Place attachment and preferences for wind energy – A value-based approach.” Energy Research & Social Science, 100, 103094. doi:10.1016/j.erss.2023.103094.
Dugstad A, Brouwer R, Grimsrud K, Kipperberg G, Lindhjem H, Navrud S (2024). “Nature is ours! – Psychological ownership and preferences for wind energy.” Energy Economics, 129, 107239. doi:10.1016/j.eneco.2023.107239.