% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/test.R
\name{test_msel}
\alias{test_msel}
\title{Tests and confidence intervals for the parameters estimated by 
the msel function}
\usage{
test_msel(
  object,
  fn,
  fn_args = list(),
  test = "t",
  method = "classic",
  ci = "classic",
  cl = 0.95,
  se_type = "dm",
  trim = 0,
  vcov = NULL,
  iter = 100,
  generator = rnorm,
  bootstrap = NULL,
  par_ind = NULL,
  eps = max(1e-04, sqrt(.Machine$double.eps) * 10),
  n_sim = 1000,
  n_cores = 1
)
}
\arguments{
\item{object}{an object of class 'msel'. It also may be a list of two 
objects. Then \code{object[[1]]} and \code{object[[2]]} are supplied to the
arguments \code{model1} and \code{model2} of the 
\code{\link[switchSelection]{lrtest_msel}} function.}

\item{fn}{a function which returns a numeric vector and should depend on the 
elements of \code{object}. These elements should be accessed via 
\code{\link[switchSelection]{coef.msel}} or 
\code{\link[switchSelection]{predict.msel}} functions.
The first argument of \code{fn} should be an \code{object}.
Therefore \code{coef} and \code{predict} functions in \code{fn} should also
depend on \code{object}.}

\item{fn_args}{a list of additional arguments of \code{fn}.}

\item{test}{a character representing the test to be used.
If \code{test = "t"} then t-test is used.
If \code{test = "wald"} then Wald test is applied.}

\item{method}{a character representing a method used to conduct a test.
If \code{test = "t"} or \code{test = "wald"} and \code{method = "classic"} 
then p-values are calculated by using the quantiles of the standard normal 
distribution.
If \code{test = "t"} or \code{test = "wald"} and \code{method = "bootstrap"} 
then p-values are calculated by using the bootstrap as described 
in Hansen (2022).
If \code{test = "wald"} and \code{method = "score"} then score 
bootstrap Wald test of P. Kline and A. Santos (2012) is used.}

\item{ci}{a character representing the type of the confidence interval
used. Available only if \code{test = "t"}.
If \code{ci = "classic"} then quantiles of the standard normal distribution
are used to build an asymptotic confidence interval.
If \code{ci = "percentile"} then percentile bootstrap interval is applied.
If \code{ci = "bc"} then the function constructs a bias-corrected 
percentile bootstrap confidence interval of Efron (1982) as described in
Hansen (2022).}

\item{cl}{a numeric value between \code{0} and \code{1} representing
a confidence level of the confidence interval.}

\item{se_type}{a character representing a method used to estimate 
the standard errors of the outputs of \code{fn}. 
If \code{se_type = "dm"} then delta method is used.
If \code{se_type = "bootstrap"} then bootstrap is applied.}

\item{trim}{a numeric value between \code{0} and \code{1} representing
the share of bootstrap estimates to be nullified when standard errors are
estimated for \code{se_type = "bootstrap"}.}

\item{vcov}{an estimate of the asymptotic covariance matrix of the 
parameters of the model.}

\item{iter}{the number of iterations used by the score bootstrap Wald test.}

\item{generator}{a function which is used by the score bootstrap to generate
random weights. It should have an argument \code{n} representing the
number of random weights to generate. Other arguments are ignored.}

\item{bootstrap}{an object of class \code{'bootstrap_msel'} which is an 
output of the \code{\link[switchSelection]{bootstrap_msel}} function.
This object is used to retrieve the estimates of the bootstrap samples.}

\item{par_ind}{a vector of indexes of the model parameters used 
in the calculation of \code{fn}. If only necessary indexes are included then
in some cases estimation time may greatly decrease. Set \code{ind = TRUE}
in \code{\link[switchSelection]{summary.msel}} to see the indexes of the 
model parameters. If \code{eps} is a vector then \code{eps[i]} determines 
the increment used to differentiate \code{fn} with respect to the parameter
with \code{par_ind[i]}-th index.}

\item{eps}{a positive numeric value representing the increment used for the
numeric differentiation of \code{fn}. It may also be a numeric vector
such that \code{eps[i]} is an increment used to differentiate the 
\code{fn} with respect to the \code{par_ind[i]}-th parameter of the model.
Set \code{ind = TRUE} in \code{\link[switchSelection]{summary.msel}}, to see 
the indexes of the model parameters. If \code{eps[i] = 0} then derivative of 
\code{fn} with respect to \code{par_ind[i]}-th parameter is assumed 
to be zero.}

\item{n_sim}{the value passed to the \code{n_sim} argument of the
\code{\link[switchSelection]{msel}} function.}

\item{n_cores}{the value passed to the \code{n_cores} argument of the
\code{\link[switchSelection]{msel}} function.}
}
\value{
This function returns an object of class \code{'test_msel'} which is
a list. It may have the following elements:
\itemize{
\item \code{tbl} - a list with the elements described below.
\item \code{is_bootstrap} - a logical value which equals \code{TRUE} if 
bootstrap has been used.
\item \code{is_ci} - a logical value which equals \code{TRUE} if
confidence intervals were used.
\item \code{test} - the same as the input argument \code{test}.
\item \code{method} - the same as the input argument \code{method}.
\item \code{se_type} - the same as the input argument \code{se_type}.
\item \code{ci} - the same as the input argument \code{ci}.
\item \code{cl} - the same as the input argument \code{cl}.
\item \code{iter} - the same as the input argument \code{iter}.
\item \code{n_bootstrap} - an integer representing the number of 
bootstrap iterations used.
\item \code{n_val} - the length of the vector returned by \code{fn}.
}

A list \code{tbl} may have the following elements:
\itemize{
\item \code{val} - an output of the \code{fn} function.
\item \code{se} - a numeric vector such that \code{se[i]} represents 
a standard error associated with \code{val[i]}.
\item \code{p_value} - a numeric vector of p-values.
\item \code{lwr} - a numeric vector such that \code{lwr[i]} is the 
realization of the lower (left) bound of the confidence interval for the
true value of \code{val[i]}.
\item \code{upr} - a numeric vector such that \code{upr[i]} is the 
realization of the upper (right) bound of the confidence interval for the
true value of \code{val[i]}.
\item \code{stat} - a numeric vector of values of the test statistics.
}

An object of class \code{'test_msel'} has an implementation of the
\code{summary} method
\code{\link[switchSelection]{summary.test_msel}}.

In a special case when \code{test = "lr"} and \code{object} is a list of 
length \code{2} the function returns an object of class \code{'lrtest_msel'} 
since the function \code{\link[switchSelection]{lrtest_msel}} is called 
internally.
}
\description{
This function conducts various statistical tests and calculates
confidence intervals for the parameters of the model estimated via the 
\code{\link[switchSelection]{msel}} function.
}
\details{
Suppose that \eqn{\theta} is a vector of parameters of the model 
estimated via the \code{\link[switchSelection]{msel}} function and 
\eqn{g(\theta)} is a differentiable function representing \code{fn} which 
returns a \eqn{m}-dimensional vector of real values:
\deqn{g(\theta) = (g_{1}(\theta),...,g_{m}(\theta))^{T}.}

\strong{Classic and bootstrap t-test}
 
If \code{test = "t"} then for each \eqn{j\in \{1,...,m\}} the following 
hypothesis is tested:
\deqn{H_{0}:g_{j}(\theta) = 0,\qquad H_{1}:g_{j}(\theta)\ne 0.}

The test statistic is: 
\deqn{T = g_{j}(\hat{\theta})/\hat{\sigma}_{j},}

where \eqn{\hat{\sigma}} is a standard error of \eqn{g_{j}(\hat{\theta})}.

If \code{se_type = "dm"} then delta method is used to estimate 
this standard error:

\deqn{\hat{\sigma}_{j} = \sqrt{\nabla g_{j}(\hat{\theta})^{T} 
\widehat{As.Cov}(\hat{\theta})
\nabla g_{j}(\hat{\theta})},
}

where \eqn{\nabla g_{j}(\hat{\theta})} is a gradient as a column vector and
the estimate of the asymptotic covariance matrix of the estimates 
\eqn{\widehat{As.Cov}(\hat{\theta})} is provided via the \code{vcov} 
argument. Numeric differentiation is used to calculate 
\eqn{\nabla g_{j}(\hat{\theta})}.

If \code{se_type = "bootstrap"} then bootstrap is 
applied to estimate the standard error:
\deqn{\hat{\sigma}_{j} = \sqrt{\frac{1}{B - 1}\sum\limits_{b = 1}^{B} 
(g_{j}(\hat{\theta}^{(b)}) - \overline{g_{j}(\hat{\theta}^{(b)}}))^2},}

where \eqn{B} is the number of the bootstrap iterations 
\code{bootstrap$iter}, \eqn{\hat{\theta}^{(b)}} is the estimate 
associated with the \eqn{b}-th of these iterations \code{bootstrap$par[b, ]},
and \eqn{\overline{g_{j}(\hat{\theta}^{(b)})}} is a sample mean of the 
bootstrap estimates estimates:

\deqn{\overline{g_{j}(\hat{\theta}^{(b)}}) = 
\frac{1}{B}\sum\limits_{b = 1}^{B}g_{j}(\hat{\theta}^{(b)}).}

If \code{method = "classic"} it is assumed that if the null hypothesis is 
true then the asymptotic distribution of the test statistic is standard 
normal. This distribution is used for the calculation of the p-value:

\deqn{p-value = 2\min(\Phi(T), 1 - \Phi(T)),}

where \eqn{\Phi()} is a cumulative distribution function of the standard
normal distribution.

If \code{method = "bootstrap"} then p-value is calculated via the bootstrap 
as suggested by Hansen (2022):
\deqn{
p-value = \frac{1}{B}\sum\limits_{b=1}^{B} I(|T_{b} - T| > |T|),
}

where \eqn{T_{b} = g_{j}(\hat{\theta}^{(b)})/\hat{\sigma}_{j}} is the value of 
the test statistic estimated on the \code{b}-th bootstrap sample and 
\eqn{I(q)} is an indicator function which equals \eqn{1} when \eqn{q} is a 
true statement and \eqn{0} - otherwise.

\strong{Classic and bootstrap Wald test}

Suppose that \code{method = "classic"} or \code{method = "bootstrap"}.
If \code{test = "wald"} then the null hypothesis is:
\deqn{H_{0}:
\begin{cases}
g_{1}(\theta) = 0\\
g_{2}(\theta) = 0\\
\vdots\\
g_{m}(\theta) = 0\\
\end{cases}.
}

The alternative hypothesis is that there is such \eqn{j\in\{1,...,m\}} that:
\deqn{H_{1}:g_{j}(\theta)\ne 0.}

The test statistic is:
\deqn{T = g(\hat{\theta})^{T}\widehat{As.Cov}(g(\hat{\theta}))^{-1}
g(\hat{\theta}),}

where \eqn{\widehat{As.Cov}(g(\hat{\theta}))} is the estimate of the 
asymptotic covariance matrix of \eqn{g(\hat{\theta})}. 

If \code{se_type = "dm"} then delta method is used to estimate this matrix:
\deqn{\widehat{As.Cov}(g(\hat{\theta})) 
= g'(\hat{\theta})\widehat{As.Cov}(\hat{\theta}) g'(\hat{\theta})^{T},}

where \eqn{g'(\hat{\theta})} is a Jacobian matrix. Numeric differentiation
is used to calculate its elements:
\deqn{g'(\hat{\theta})_{ij} = 
\frac{\partial g_{i}(\theta)}{\partial \theta_{j}}|_{\theta = \hat{\theta}}.}

If \code{se_type = "bootstrap"} then bootstrap is used to estimate this 
matrix:
\deqn{\widehat{As.Cov}(g(\hat{\theta}))=
\frac{1}{B-1}\sum\limits_{i=1}^{B}q_{b}q_{b}^{T},}
where:
\deqn{q_{b} = (g(\hat{\theta}^{(b)}) - 
\overline{g(\hat{\theta}^{(b)})}),}
\deqn{\overline{g(\hat{\theta}^{(b)})} = \frac{1}{B}\sum\limits_{i=1}^{B}
g(\hat{\theta}^{(b)}).}

If \code{method = "classic"} then it is assumed that if the null hypothesis 
is true then the asymptotic distribution of the test statistic is chi-squared
with \eqn{m} degrees of freedom. This distribution is used for the 
calculation of the p-value:

\deqn{p-value = 1 - F_{m}(T),}

where \eqn{F_{m}} is a cumulative distribution function of the chi-squared
distribution with \eqn{m} degrees of freedom.

If \code{method = "bootstrap"} then p-value is calculated via the bootstrap 
as suggested by Hansen (2022):
\deqn{
p-value = \frac{1}{B}\sum\limits_{b=1}^{B} I(T_{b} > T),
}
where:
\deqn{T_{b} = s_{b}^{T}\widehat{As.Cov}(g(\hat{\theta}))^{-1}s_{b},}
\deqn{s_{b} = g(\hat{\theta}^{(b)}) - g(\hat{\theta}).}

\strong{Score bootstrap Wald test}

If \code{method = "score"} and \code{test = "Wald"} then score bootstrap
Wald test of Kline and Santos (2012) is used.

Consider \eqn{B} independent samples of \eqn{n} independent identically 
distributed random weights with zero mean and unit variance. 
Let \eqn{w_{ib}} denote the \eqn{i}-th weight of the \eqn{b}-th sample. 
Argument \code{generator} is used to supply a function which generates these 
weights \eqn{w_{ib}} and \code{iter} argument represents \eqn{B}. 
Also \eqn{n} is the number of observations in the model 
\code{object$other$n_obs}.

Let \eqn{J} denote a matrix of sample scores \code{object$J}. 
Further, denote by \eqn{J_{b}} a matrix such that its \eqn{b}-th row is a 
product of the \eqn{w_{ib}} and the \eqn{b}-th row of \eqn{J}. 
Also, denote by \eqn{H} a matrix of mean values of the derivatives of 
sample scores with respect to the estimated parameters \code{object$H}.

In addition consider the following notations:
\deqn{A = g'(\theta) H^{-1}, \qquad S_{b} = A J^{(c)}_{b},}
where \eqn{J^{(c)}_{b}} is a vector of the column sums of \eqn{J_{b}}.

The test statistic is as follows:
\deqn{T = g(\hat{\theta})^{T}(A\widehat{Cov}(J)
A^{T})^{-1}g(\hat{\theta}) / n,}
where \eqn{\widehat{Cov}(J)} is a sample covariance matrix of the sample
scores of the model \code{cov(object$J)}.

The test statistic on the \eqn{b}-th bootstrap sample is similar:
\deqn{T_{b} = S^{T}(A\widehat{Cov}(J_{b})
A^{T})^{-1}S / n.}

The p-value is estimated as follows:
\deqn{
p-value = \frac{1}{B}\sum\limits_{b=1}^{B} I(T_{b} > T).
}

\strong{Confidence intervals}

If \code{test = "t"} then the function also returns the realizations of the 
lower and upper bounds of the \eqn{100 \times}\code{cl} percent symmetric 
asymptotic confidence interval of \eqn{g_{j}(\theta)}.

If \code{ci = "classic"} then classic confidence interval is used which
assumes asymptotic normality of \eqn{g_{j}(\hat{\theta})}:
\deqn{(g_{j}(\hat{\theta}) + z_{(1 - cl) / 2}\hat{\sigma}_{j}, 
g_{j}(\hat{\theta}) + z_{1 - (1 - cl) / 2}\hat{\sigma}_{j}),}
where \eqn{z_{q}} is the \eqn{q}-th quantile of the standard normal 
distribution and \eqn{cl} is a confidence level \code{cl}. The method used 
to estimate \eqn{\hat{\sigma}_{j}} depends on the \code{se_type} argument as 
described above.

If \code{ci = "percentile"} then percentile bootstrap confidence interval 
is used. Therefore the sample quantiles of \eqn{g_{j}(\hat{\theta}^{(b)})} 
are used as the realizations of the lower and upper bounds of the confidence 
interval.

If \code{ci = "bc"} then bias-corrected percentile bootstrap confidence 
interval of Efron (1982) is used as described in Hansen (2022). The default
percentile bootstrap confidence interval uses sample quantiles of levels 
\eqn{(1 - cl)/2} and \eqn{1 - (1 - cl)/2}. 
Bias-corrected version uses the sample quantiles of the
following levels:
\deqn{(1 - cl)/2 + \Phi(\Phi^{-1}((1 - cl)/2) + s),}
\deqn{1 - (1 - cl)/2 + \Phi(\Phi^{-1}(1 - (1 - cl)/2) + s),}
where:
\deqn{s = 2\Phi^{-1}(\frac{1}{B}\sum\limits_{b = 1}^{B}
I(g_{j}(\hat{\theta}^{(b)})\leq g_{j}(\hat{\theta}))).}

\strong{Trimming}

If \code{se_type = "bootstrap"} and \code{trim > 0} then trimming is used as
described in Hansen (2022) to estimate \eqn{\hat{\sigma}_{j}} and 
\eqn{\widehat{As.Cov}(g(\hat{\theta}))}. The algorithm is as follows. 
First, nullify 100\code{trim} percent of \eqn{g(\hat{\theta}^{(b)})} with the 
greatest values of the L2-norm of \eqn{q_{b}} (defined above). 
Then use this 'trimmed' sample to estimate the standard error and the 
asymptotic covariance matrix.

\strong{Cross-model tests}

It is also possible to test the hypothesis on the parameters estimated
via several different models. To do so it is necessary to provide a list of 
models (objects of class \code{msel}) via the \code{object} argument. 
Particularly, cross-model tests are useful for comparing marginal and 
treatment effects among the different models. In addition, cross-model
tests may be used for testing over-identifying restrictions.

If \code{se_type = "dm"} then the joint covariance matrix of the estimators 
is obtained via the stacking method similar to one implemented by 
\code{suest} postestimation command in \code{STATA}. Note that there are 
the following requirements:
\itemize{
\item Covariance matrix type \code{cov_type} of each \code{object[[i]]} 
should be either \code{"mm"} or \code{"sandwich"}. 
\item Argument \code{data}  of each \code{object[[i]]} should contain a 
special variable \code{crossind}. Suppose that each \code{object[[i]]$data} 
is a subsample of some \code{data0}. Then \code{crossind} argument should 
take different values in range between \code{1} and \code{nrow(data0)}. 
In addition, observations with the same value of \code{crossind} in 
\code{object[[i]]$data} should correspond to the same observation 
in \code{data0}. A simple way to create \code{crossind} variable is just to
set it equal to \code{1:nrow(data0)} in \code{data0} before splitting it
into subsamples used by the models.
\item Argument \code{cluster} of each \code{object[[i]]} is ignored. However,
clustering may be provided via \code{crosscluster} variable in 
\code{object[[i]]$data}. Then observations with the same value of 
\code{crosscluster} are considered to be from the same cluster.
}

Arguments \code{eps} and \code{par_ind} may be lists whose elements are 
associated with the corresponding models. If \code{eps} is a scalar, then the 
same increment will be used for the numeric differentiation with respect to 
parameters of all models. Also, by default indexes of all parameters of all 
the models will be included in \code{par_ind}.
}
\examples{
\donttest{

# -------------------------------
# CPS data example
# -------------------------------

# Set seed for reproducibility
set.seed(123)

# Load the data
data(cps)

# Estimate the employment model
model <- msel(work ~ age + I(age ^ 2) + bachelor + master, data = cps)
summary(model)    

# Use Wald test to test the hypothesis that age has no 
# effect on the conditional probability of employment:
# H0: coef age     = 0
#     coef age ^ 2 = 0
age_fn <- function(object)
{
  lwage_coef <- coef(object, type = "coef")[[1]]
  val        <- c(lwage_coef["age"], lwage_coef["I(age^2)"])
  return(val)
}
age_test <- test_msel(object = model, fn = age_fn, test = "wald")
summary(age_test)

# Use t-test to test for each individual the hypothesis:
# P(work = 1 | x) = 0.8
prob_fn <- function(object)
{
  prob <- predict(object, group = 1, type = "prob")
  val  <- prob - 0.8
  return(val)
}
prob_test <- test_msel(object = model, fn = prob_fn, test = "t")
summary(prob_test)

# -------------------------------
# Simulated data example
# Model with continuous outcome
# and ordinal selection
# -------------------------------

# ---
# Step 1
# Simulation of the data
# ---

# Set seed for reproducibility
set.seed(123)

# Load required package
library("mnorm")

# The number of observations
n <- 10000

# Regressors (covariates)
s1 <- runif(n = n, min = -1, max = 1)
s2 <- runif(n = n, min = -1, max = 1)
s3 <- runif(n = n, min = -1, max = 1)
s4 <- runif(n = n, min = -1, max = 1)

# Random errors
sigma <- matrix(c(1,    0.4,  0.45, 0.7,
                  0.4,  1,    0.54, 0.8,
                  0.45, 0.54, 0.81, 0.81,
                  0.7,  0.8,  0.81, 1), nrow = 4)
errors <- mnorm::rmnorm(n = n, mean = c(0, 0, 0, 0), sigma = sigma)
u1   <- errors[, 1]
u2   <- errors[, 2]
eps0 <- errors[, 3]
eps1 <- errors[, 4]

# Coefficients
gamma1     <- c(-1, 2)
gamma2     <- c(1, 1)
gamma1_het <- c(0.5, -1)
beta0      <- c(1, -1, 1, -1.2)
beta1      <- c(2, -1.5, 0.5, 1.2)
# Linear index of the ordinal equations
# mean part
li1 <- gamma1[1] * s1 + gamma1[2] * s2
li2 <- gamma2[1] * s1 + gamma2[2] * s3
# variance part
li1_het <- gamma1_het[1] * s2 + gamma1_het[2] * s3

# Linear index of the continuous equation
# regime 0
li_y0 <- beta0[1] + beta0[2] * s1 + beta0[3] * s3 + beta0[4] * s4
# regime 1
li_y1 <- beta1[1] + beta1[2] * s1 + beta1[3] * s3 + beta1[4] * s4

# Latent variables
z1_star <- li1 + u1 * exp(li1_het)
z2_star <- li2 + u2
y0_star <- li_y0 + eps0
y1_star <- li_y1 + eps1

# Cuts
cuts1 <- c(-1)
cuts2 <- c(0, 1)

# Observable ordinal outcome
# first
z1                     <- rep(0, n)
z1[z1_star > cuts1[1]] <- 1
# second
z2                                               <- rep(0, n)
z2[(z2_star > cuts2[1]) & (z2_star <= cuts2[2])] <- 1
z2[z2_star > cuts2[2]]                           <- 2
z2[z1 == 0]                                      <- NA

# Observable continuous outcome
y                 <- rep(NA, n)
y[which(z2 == 0)] <- y0_star[which(z2 == 0)]
y[which(z2 != 0)] <- y1_star[which(z2 != 0)]
y[which(z1 == 0)] <- NA

# Data
data <- data.frame(s1 = s1, s2 = s2, s3 = s3, s4 = s4,
                   z1 = z1, z2 = z2, y = y,   crossind = 1:n)

# ---
# Step 2
# Estimation of the parameters
# ---

# Assign the groups
groups  <- matrix(c(1, 2,
                    1, 1,
                    1, 0,
                    0, -1), 
                  byrow = TRUE, ncol = 2)
groups2 <- matrix(c(1, 1, 0, -1), ncol = 1)

# Estimate the model
model <- msel(list(z1 ~ s1 + s2 | s2 + s3,
                   z2 ~ s1 + s3),
              list(y  ~ s1 + s3 + s4),
              groups = groups, groups2 = groups2, 
              data   = data)
                   
# ---
# Step 3
# Hypotheses testing
# ---

# Use t-test to test for each observation the hypothesis
# H0: P(z1 = 1, z2 = 0 | Xi) = 0 
prob02_fn <- function(object)
{
   val <- predict(object, group = c(1, 0))
   
   return(val)
}
prob02_test <- test_msel(object = model, fn = prob02_fn, test = "t")
summary(prob02_test)

# Use t-test to test the hypothesis
# H0: E(y1|z1=0, z2=2) - E(y0|z1=0, z2=2)
ATE_fn <- function(object)
{
   val1 <- predict(object, group = c(0, 2), group2 = 1)
   val0 <- predict(object, group = c(0, 2), group2 = 0)
   val <- mean(val1 - val0)
   
   return(val)
}
ATE_test <- test_msel(object = model, fn = ATE_fn)
summary(ATE_test)

# Use Wald test to test the hypothesis
# H0: beta1 = beta0
coef_fn <- function(object)
{
   coef1 <- coef(object, regime = 1, type = "coef2")
   coef0 <- coef(object, regime = 0, type = "coef2")
   coef_difference <- coef1 - coef0
   
   return(coef_difference)
}
coef_test <- test_msel(object = model, fn = coef_fn, test = "wald")
summary(coef_test)

# Use t-test to test for each 'k' the hypothesis
# H0: beta1k = beta0k
coef_test2 <- test_msel(object = model, fn = coef_fn, test = "t")
summary(coef_test2)

# Use Wald test to test the hypothesis
# H0: beta11 + beta12 - 0.5 = 0
#     beta11 * beta13 - beta03 = 0
test_fn <- function(object)
{
  coef1 <- coef(object, regime = 1, type = "coef2")
  coef0 <- coef(object, regime = 0, type = "coef2")
  val   <- c(coef1[1] + coef1[2] - 0.5, 
  coef1[1] * coef1[3] - coef0[3])
     
  return(val)
}
# classic Wald test
wald1 <- test_msel(object = model,  fn     = test_fn, 
                   test   = "wald", method = "classic")
summary(wald1)
# score bootstrap Wald test
wald2 <- test_msel(object = model,  fn     = test_fn, 
                   test   = "wald", method = "score")
summary(wald2)

# Replicate the latter test with the 2-step estimator
model2 <- msel(list(z1 ~ s1 + s2 | s2 + s3,
                         z2 ~ s1 + s3),
               list(y ~ s1 + s3 + s4),
               groups    = groups, groups2   = groups2, 
               data      = data,   estimator = "2step")
# classic Wald test
wald1_2step <- test_msel(object = model2, fn     = test_fn, 
                         test   = "wald", method = "classic")
summary(wald1_2step)
# score bootstrap Wald test
wald2_2step <- test_msel(object = model2, fn     = test_fn, 
                         test   = "wald", method = "score")
summary(wald2_2step)    

# ---
# Step 4
# Cross-model tests
# ---

# Use Wald test to test the hypothesis that coefficients
# in regime 1 are the same in both models
cmtest_fn <- function(object)
{
  coef1 <- coef(object[[1]], regime = 1, type = "coef2")
  coef2 <- coef(object[[2]], regime = 1, type = "coef2")
  val   <- coef1 - coef2
  
  return(val)
}

# Classic Wald test
test_wald <- test_msel(object = list(model, model2), fn     = cmtest_fn, 
                       test   = "wald",              method = "classic")
summary(test_wald)


# Score bootstrap Wald test
test_score <- test_msel(object = list(model, model2), fn     = cmtest_fn, 
                        test   = "wald",              method = "score")
summary(test_score)

}
             
}
\references{
B. Efron (1982). The Jackknife, the Bootstrap, and Other 
Resampling Plans. Society for Industrial and Applied Mathematics.

B. Hansen (2022). Econometrics. Princeton University Press.

P. Kline, A. Santos (2012). 
A Score Based Approach to Wild Bootstrap Inference.
Journal of Econometric Methods, vol. 67, no. 1, pages 23-41.
}
