% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/binspwc.R
\name{binspwc}
\alias{binspwc}
\title{Data-Driven Pairwise Group Comparison using Binscatter Methods}
\usage{
binspwc(y, x, w = NULL, data = NULL, estmethod = "reg",
  family = gaussian(), quantile = NULL, deriv = 0, at = NULL,
  nolink = F, by = NULL, pwc = NULL, testtype = "two-sided",
  lp = Inf, bins = NULL, bynbins = NULL, binspos = "qs",
  pselect = NULL, sselect = NULL, binsmethod = "dpi", nbinsrot = NULL,
  samebinsby = FALSE, randcut = NULL, nsims = 500, simsgrid = 20,
  simsseed = NULL, vce = NULL, cluster = NULL, asyvar = F,
  dfcheck = c(20, 30), masspoints = "on", weights = NULL,
  subset = NULL, numdist = NULL, numclust = NULL, estmethodopt = NULL,
  plot = FALSE, printplot = TRUE, dotsngrid = 0, plotxrange = NULL,
  plotyrange = NULL, colors = NULL, symbols = NULL, level = 95, ...)
}
\arguments{
\item{y}{outcome variable. A vector.}

\item{x}{independent variable of interest. A vector.}

\item{w}{control variables. A matrix, a vector or a \code{\link{formula}}.}

\item{data}{an optional data frame containing variables used in the model.}

\item{estmethod}{estimation method. The default is \code{estmethod="reg"} for tests based on binscatter least squares regression. Other options are \code{"qreg"} for quantile regression and \code{"glm"} for generalized linear regression. If \code{estmethod="glm"}, the option \code{family} must be specified.}

\item{family}{a description of the error distribution and link function to be used in the generalized linear model when \code{estmethod="glm"}. (See \code{\link{family}} for details of family functions.)}

\item{quantile}{the quantile to be estimated. A number strictly between 0 and 1.}

\item{deriv}{derivative order of the regression function for estimation, testing and plotting.
The default is \code{deriv=0}, which corresponds to the function itself.}

\item{at}{value of \code{w} at which the estimated function is evaluated.  The default is \code{at="mean"}, which corresponds to
the mean of \code{w}. Other options are: \code{at="median"} for the median of \code{w}, \code{at="zero"} for a vector of zeros.
\code{at} can also be a vector of the same length as the number of columns of \code{w} (if \code{w} is a matrix) or a data frame containing the same variables as specified in \code{w} (when
\code{data} is specified). Note that when \code{at="mean"} or \code{at="median"}, all factor variables (if specified) are excluded from the evaluation (set as zero).}

\item{nolink}{if true, the function within the inverse link function is reported instead of the conditional mean function for the outcome.}

\item{by}{a vector containing the group indicator for subgroup analysis; both numeric and string variables
are supported. When \code{by} is specified, \code{binsreg} implements estimation and inference for each subgroup
separately, but produces a common binned scatter plot. By default, the binning structure is selected for each
subgroup separately, but see the option \code{samebinsby} below for imposing a common binning structure across subgroups.}

\item{pwc}{a vector or a logical value. If \code{pwc=c(p,s)}, a piecewise polynomial of degree \code{p} with \code{s}
smoothness constraints is used for testing the difference between groups.
If \code{pwc=T} or \code{pwc=NULL} (default) is specified, \code{pwc=c(1,1)} is used unless the degree \code{p} or smoothness \code{s} selection
is requested via the option \code{pselect} or \code{sselect} (see more details in the explanation of \code{pselect} and \code{sselect}).}

\item{testtype}{type of pairwise comparison test. The default is \code{testtype="two-sided"}, which corresponds to a two-sided test of the form \code{H0: mu_1(x)=mu_2(x)}.
Other options are: \code{testtype="left"} for the one-sided test form \code{H0: mu_1(x)<=mu_2(x)} and \code{testtype="right"} for the one-sided test of the form \code{H0: mu_1(x)>=mu_2(x)}.}

\item{lp}{an Lp metric used for pairwise comparison tests. The default is \code{lp=Inf}, which
corresponds to the sup-norm of the t-statistic. Other options are \code{lp=q} for a positive number \code{q>=1}.
Note that \code{lp=Inf} ("sup-norm") has to be used for one-sided tests (\code{testtype="left"} or \code{testtype="right"}).}

\item{bins}{A vector. If \code{bins=c(p,s)}, it sets the piecewise polynomial of degree \code{p} with \code{s} smoothness constraints
for data-driven (IMSE-optimal) selection of the partitioning/binning scheme. The default is \code{bins=c(0,0)}, which corresponds to the piecewise constant.}

\item{bynbins}{a vector of the number of bins for partitioning/binning of \code{x}, which is applied to the binscatter estimation for each group.
If a single number is specified, it is applied to the estimation for all groups.
If \code{bynbins=T} or \code{bynbins=NULL} (default), the number of bins is selected via the companion function \code{\link{binsregselect}}
in a data-driven way whenever possible.
\emph{Note:} If a vector with more than one number is supplied, it is understood as the number of bins applied to binscatter estimation
for each subgroup rather than the range for selecting the number of bins.}

\item{binspos}{position of binning knots. The default is \code{binspos="qs"}, which corresponds to quantile-spaced
binning (canonical binscatter).  The other options are \code{"es"} for evenly-spaced binning, or
a vector for manual specification of the positions of inner knots (which must be within the range of \code{x}).}

\item{pselect}{vector of numbers within which the degree of polynomial \code{p} for point estimation is selected.
If the selected optimal degree is \code{p}, then piecewise polynomials of degree \code{p+1} are used to
conduct pairwise group comparison. \emph{Note:} To implement the degree or smoothness selection, in addition to \code{pselect} or \code{sselect},
\code{bynbins=#} must be specified.}

\item{sselect}{vector of numbers within which the number of smoothness constraints \code{s} for point estimation is selected.
 If the selected optimal smoothness is \code{s}, then piecewise polynomials with \code{s+1} smoothness constraints
 are used to conduct pairwise group comparison.
If not specified, for each value \code{p} supplied in the option \code{pselect}, only the
piecewise polynomial with the maximum smoothness is considered, i.e., \code{s=p}.}

\item{binsmethod}{method for data-driven selection of the number of bins. The default is \code{binsmethod="dpi"},
which corresponds to the IMSE-optimal direct plug-in rule.  The other option is: \code{"rot"}
for rule of thumb implementation.}

\item{nbinsrot}{initial number of bins value used to construct the DPI number of bins selector.
If not specified, the data-driven ROT selector is used instead.}

\item{samebinsby}{if true, a common partitioning/binning structure across all subgroups specified by the option \code{by} is forced.
The knots positions are selected according to the option \code{binspos} and using the full sample. If \code{nbins}
is not specified, then the number of bins is selected via the companion command \code{\link{binsregselect}} and
using the full sample.}

\item{randcut}{upper bound on a uniformly distributed variable used to draw a subsample for bins/degree/smoothness selection.
Observations for which \code{runif()<=#} are used. # must be between 0 and 1. By default, \code{max(5000, 0.01n)} observations
are used if the samples size \code{n>5000}.}

\item{nsims}{number of random draws for hypothesis testing. The default is
\code{nsims=500}, which corresponds to 500 draws from a standard Gaussian random vector of size
\code{[(p+1)*J - (J-1)*s]}. Setting at least \code{nsims=2000} is recommended to obtain the final results.}

\item{simsgrid}{number of evaluation points of an evenly-spaced grid within each bin used for evaluation of
the supremum (infimum or Lp metric) operation needed to construct hypothesis testing
procedures. The default is \code{simsgrid=20}, which corresponds to 20 evenly-spaced
evaluation points within each bin for approximating the supremum (infimum or Lp metric) operator.
Setting at least \code{simsgrid=50} is recommended to obtain the final results.}

\item{simsseed}{seed for simulation.}

\item{vce}{procedure to compute the variance-covariance matrix estimator. For least squares regression and generalized linear regression, the allowed options are the same as that for \code{\link{binsreg}} or \code{\link{binsqreg}}.
For quantile regression, the allowed options are the same as that for \code{\link{binsqreg}}.}

\item{cluster}{cluster ID. Used for compute cluster-robust standard errors.}

\item{asyvar}{if true, the standard error of the nonparametric component is computed and the uncertainty related to control
variables is omitted. Default is \code{asyvar=FALSE}, that is, the uncertainty related to control variables is taken into account.}

\item{dfcheck}{adjustments for minimum effective sample size checks, which take into account number of unique
values of \code{x} (i.e., number of mass points), number of clusters, and degrees of freedom of
the different stat models considered. The default is \code{dfcheck=c(20, 30)}.
See \href{https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2025_Stata.pdf}{Cattaneo, Crump, Farrell and Feng (2025)} for more details.}

\item{masspoints}{how mass points in \code{x} are handled. Available options:
\itemize{
\item \code{"on"} all mass point and degrees of freedom checks are implemented. Default.
\item \code{"noadjust"} mass point checks and the corresponding effective sample size adjustments are omitted.
\item \code{"nolocalcheck"} within-bin mass point and degrees of freedom checks are omitted.
\item \code{"off"} "noadjust" and "nolocalcheck" are set simultaneously.
\item \code{"veryfew"} forces the function to proceed as if \code{x} has only a few number of mass points (i.e., distinct values).
                       In other words, forces the function to proceed as if the mass point and degrees of freedom checks were failed.
}}

\item{weights}{an optional vector of weights to be used in the fitting process. Should be \code{NULL} or
a numeric vector. For more details, see \code{\link{lm}}.}

\item{subset}{optional rule specifying a subset of observations to be used.}

\item{numdist}{number of distinct values for selection. Used to speed up computation.}

\item{numclust}{number of clusters for selection. Used to speed up computation.}

\item{estmethodopt}{a list of optional arguments used by \code{\link[quantreg]{rq}} (for quantile regression) or \code{\link{glm}} (for fitting generalized linear models).}

\item{plot}{if true, the confidence bands for all pairwise group comparisons (the difference between each pair of groups) are plotted.
The degree and smoothness of polynomials used to construct the bands are the same as those specified for testing. The default is \code{plot=F}, i.e.,
no plot is generated.}

\item{printplot}{if true, the generated \code{ggplot} object is printed when \code{plot=TRUE}. If false, the plot object is returned without printing.}

\item{dotsngrid}{number of dots to be added to the plot for confidence bands. Given the choice, these dots are point estimates of the difference between groups
evaluated over an evenly-spaced grid within the common support of all groups. The default is \code{dotsngrid=0}, i.e., no point estimates
are added. Whenever possible, the degree and smoothness of the polynomial for these point estimates are the same as those for selecting the number of bins;
otherwise, the degree and smoothness specified for testing are used.}

\item{plotxrange}{a vector. \code{plotxrange=c(min, max)} specifies a range of the x-axis for plotting. Observations outside the range are dropped in the plot.}

\item{plotyrange}{a vector. \code{plotyrange=c(min, max)} specifies a range of the y-axis for plotting. Observations outside the range are dropped in the plot.}

\item{colors}{an ordered list of colors for plotting the difference between each pair of groups.}

\item{symbols}{an ordered list of symbols for plotting the difference between each pair of groups.}

\item{level}{nominal confidence level for confidence band estimation. Default is \code{level=95}.}

\item{...}{optional arguments to control bootstrapping if \code{estmethod="qreg"} and \code{vce="boot"}. See \code{\link[quantreg]{boot.rq}}.}
}
\value{
\item{\code{tstat}}{A matrix. Each row corresponds to the comparison between two groups. The first column is the test statistic. The second and third columns give the corresponding group numbers.
                          The null hypothesis is \code{mu_i(x)<=mu_j(x)}, \code{mu_i(x)=mu_j(x)}, or \code{mu_i(x)>=mu_j(x)} for group i (given in the second column) and group j (given in the third column).
                          The group number corresponds to the list of group names given by \code{opt$byvals}.}
       \item{\code{pval}}{A vector of p-values for all pairwise group comparisons.}
       \item{\code{bins_plot}}{A \code{ggplot} object for confidence bands plot.}
       \item{\code{data.plot}}{A list containing data for plotting. Each item is a sublist of data frames for comparison between each pair of groups. Each sublist may contain the following data frames:
       \itemize{
       \item \code{data.dots} Data for dots. It contains: \code{pair}, the name for the pair of groups; \code{x}, evaluation points; \code{diff.fit}, point estimates of the group difference;
       \item \code{data.cb} Data for confidence bands. It contains: \code{pair}, the name for the pair of groups; \code{x}, evaluation points; \code{cb.fit}, point estimates of the group difference;
                            \code{cb.se}, standard errors; \code{cb.l} and \code{cb.r}, left and right boundaries of the confidence band.
       }
       }
       \item{\code{cval.cb}}{A vector of critical values for all pairwise group comparisons.}
       \item{\code{imse.var.rot}}{Variance constant in IMSE expansion, ROT selection.}
       \item{\code{imse.bsq.rot}}{Bias constant in IMSE expansion, ROT selection.}
       \item{\code{imse.var.dpi}}{Variance constant in IMSE expansion, DPI selection.}
       \item{\code{imse.bsq.dpi}}{Bias constant in IMSE expansion, DPI selection.}
       \item{\code{opt}}{ A list containing options passed to the function, as well as \code{N.by} (total sample size for each group),
                          \code{Ndist.by} (number of distinct values in \code{x} for each group), \code{Nclust.by} (number of clusters for each group),
                          and \code{nbins.by} (number of bins for each group), and \code{byvals} (number of distinct values in \code{by}).}
       \item{\code{call}}{The matched function call.}
}
\description{
\code{binspwc} implements hypothesis testing procedures for pairwise group comparison of binscatter estimators
            and plots confidence bands for the difference in binscatter parameters between each pair of groups, following the
            results in \href{https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2024_AER.pdf}{Cattaneo, Crump, Farrell and Feng (2024)} and
            \href{https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2026_RESTAT.pdf}{Cattaneo, Crump, Farrell and Feng (2026)}.
            If the binning scheme is not set by the user, the companion function
            \code{\link{binsregselect}} is used to implement binscatter in a data-driven way. Binned scatter plots based on different methods
            can be constructed using the companion functions \code{\link{binsreg}}, \code{\link{binsqreg}} or \code{\link{binsglm}}.
            Hypothesis testing for parametric functional forms of and shape restrictions on the regression function of interest can
            be conducted via the companion function \code{\link{binstest}}.
}
\examples{
 x <- runif(500); y <- sin(x)+rnorm(500); t <- 1*(runif(500)>0.5)
 ## Binned scatterplot
 binspwc(y,x, by=t)
}
\references{
Cattaneo, M. D., R. K. Crump, M. H. Farrell, and Y. Feng. 2024: \href{https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2024_AER.pdf}{On Binscatter}. American Economic Review 114(5): 1488-1514.

Supplemental Appendix for On Binscatter: \href{https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2024_AER--Supplemental.pdf}{Supplemental Appendix}.

Cattaneo, M. D., R. K. Crump, M. H. Farrell, and Y. Feng. 2026: \href{https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2026_RESTAT.pdf}{Nonlinear Binscatter Methods}. Review of Economics and Statistics, revise and resubmit.

Supplemental Appendix for Nonlinear Binscatter Methods: \href{https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2026_RESTAT--Supplemental.pdf}{Supplemental Appendix}.

Cattaneo, M. D., R. K. Crump, M. H. Farrell, and Y. Feng. 2025: \href{https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2025_Stata.pdf}{Binscatter Regressions}. Stata Journal 25(1): 3-50.
}
\seealso{
\code{\link{binsreg}}, \code{\link{binsqreg}}, \code{\link{binsglm}}, \code{\link{binsregselect}}, \code{\link{binstest}}.
}
\author{
Matias D. Cattaneo (maintainer). \email{matias.d.cattaneo@gmail.com}.

Richard K. Crump. \email{richard.crump@gmail.com}.

Max H. Farrell. \email{mhfarrell@gmail.com}.

Yingjie Feng. \email{fengyingjiepku@gmail.com}.
}
