Kernel Distribution Bandwidth Selection with Mixed Data Types
np.distribution.bw.Rdnpudistbw computes a bandwidth object for a \(p\)-variate
kernel cumulative distribution estimator defined over mixed continuous
and discrete (ordered) data using either the normal reference
rule-of-thumb or least-squares cross validation using the method of
Li, Li and Racine (2017).
Usage
npudistbw(...)
# S3 method for class 'formula'
npudistbw(formula,
data,
subset,
na.action,
call,
gdata = NULL,
...)
# S3 method for class 'dbandwidth'
npudistbw(dat = stop("invoked without input data 'dat'"),
bws,
gdat = NULL,
bandwidth.compute = TRUE,
cfac.dir = 2.5*(3.0-sqrt(5)),
scale.factor.init = 0.5,
dfac.dir = 0.25*(3.0-sqrt(5)),
dfac.init = 0.375,
dfc.dir = 3,
do.full.integral = FALSE,
ftol = 1.490116e-07,
scale.factor.init.upper = 2.0,
hbd.dir = 1,
hbd.init = 0.9,
initc.dir = 1.0,
initd.dir = 1.0,
invalid.penalty = c("baseline","dbmax"),
itmax = 10000,
lbc.dir = 0.5,
scale.factor.init.lower = 0.1,
lbd.dir = 0.1,
lbd.init = 0.1,
memfac = 500.0,
ngrid = 100,
nmulti,
penalty.multiplier = 10,
powell.remin = TRUE,
bwsolver = c("powell", "mads", "mads+powell"),
scale.init.categorical.sample = FALSE,
scale.factor.search.lower = NULL,
small = 1.490116e-05,
tol = 1.490116e-04,
transform.bounds = FALSE,
eval.only = FALSE,
...)
# Default S3 method
npudistbw(dat = stop("invoked without input data 'dat'"),
bws,
gdat,
bandwidth.compute = TRUE,
bwmethod,
bwscaling,
bwtype,
cfac.dir,
scale.factor.init,
ckerbound,
ckerlb,
ckerorder,
ckertype,
ckerub,
dfac.dir,
dfac.init,
dfc.dir,
do.full.integral,
ftol,
scale.factor.init.upper,
hbd.dir,
hbd.init,
initc.dir,
initd.dir,
invalid.penalty,
itmax,
lbc.dir,
scale.factor.init.lower,
lbd.dir,
lbd.init,
memfac,
ngrid,
nmulti,
okertype,
penalty.multiplier,
powell.remin,
bwsolver = c("powell", "mads", "mads+powell"),
scale.init.categorical.sample,
scale.factor.search.lower = NULL,
small,
tol,
transform.bounds,
...)Arguments
Data, Bandwidth Inputs And Formula Interface
These arguments identify the data, formula interface, optional integration grid, and whether bandwidths are supplied or computed.
- bandwidth.compute
a logical value which specifies whether to do a numerical search for bandwidths or not. If set to
FALSE, abandwidthobject will be returned with bandwidths set to those specified inbws. Defaults toTRUE.- bws
a bandwidth specification. This can be set as a bandwidth object returned from a previous invocation, or as a vector of bandwidths, with each element \(i\) corresponding to the bandwidth for column \(i\) in
dat. In either case, the bandwidth supplied will serve as a starting point in the numerical search for optimal bandwidths. If specified as a vector, then additional arguments will need to be supplied as necessary to specify the bandwidth type, kernel types, selection methods, and so on. This can be left unset.- call
the original function call. This is passed internally by
npwhen a bandwidth search has been implied by a call to another function. It is not recommended that the user set this.- dat
a \(p\)-variate data frame on which bandwidth selection will be performed. The data types may be continuous, discrete (ordered factors), or some combination thereof.
- data
an optional data frame, list or environment (or object coercible to a data frame by
as.data.frame) containing the variables in the model. If not found in data, the variables are taken fromenvironment(formula), typically the environment from which the function is called.- formula
a symbolic description of variables on which bandwidth selection is to be performed. The details of constructing a formula are described below.
- gdat
a grid of data on which the indicator function for least-squares cross-validation is to be computed (can be the sample or a grid of quantiles).
- gdata
a grid of data on which the indicator function for least-squares cross-validation is to be computed (can be the sample or a grid of quantiles).
- na.action
a function which indicates what should happen when the data contain
NAs. The default is set by thena.actionsetting of options, and isna.failif that is unset. The (recommended) default isna.omit.- subset
an optional vector specifying a subset of observations to be used in the fitting process.
Bandwidth Criterion And Representation
These arguments choose the selection criterion and the way continuous bandwidths are represented.
- bwmethod
a character string specifying the bandwidth selection method.
cv.cdfspecifies least-squares cross-validation for cumulative distribution functions (Li, Li and Racine (2017)), andnormal-referencejust computes the ‘rule-of-thumb’ bandwidth \(h_j\) using the standard formula \(h_j = 1.587 \sigma_j n^{-1/(P+l)}\), where \(\sigma_j\) is an adaptive measure of spread of the \(j\)th continuous variable defined as min(standard deviation, mean absolute deviation/1.4826, interquartile range/1.349), \(n\) the number of observations, \(P\) the order of the kernel, and \(l\) the number of continuous variables. Note that when there exist factors and the normal-reference rule is used, there is zero smoothing of the factors. Defaults tocv.cdf.- bwscaling
a logical value that when set to
TRUEthe supplied bandwidths are interpreted as ‘scale factors’ (\(c_j\)), otherwise when the value isFALSEthey are interpreted as ‘raw bandwidths’ (\(h_j\) for continuous data types, \(\lambda_j\) for discrete data types). For continuous data types, \(c_j\) and \(h_j\) are related by the formula \(h_j = c_j \sigma_j n^{-1/(P+l)}\), where \(\sigma_j\) is an adaptive measure of spread of the \(j\)th continuous variable defined as min(standard deviation, mean absolute deviation/1.4826, interquartile range/1.349), \(n\) the number of observations, \(P\) the order of the kernel, and \(l\) the number of continuous variables. For discrete data types, \(c_j\) and \(h_j\) are related by the formula \(h_j = c_jn^{-2/(P+l)}\), where here \(j\) denotes discrete variable \(j\). Defaults toFALSE.- bwtype
character string used for the continuous variable bandwidth type, specifying the type of bandwidth to compute and return in the
bandwidthobject. Defaults tofixed. Option summary:fixed: compute fixed bandwidthsgeneralized_nn: compute generalized nearest neighborsadaptive_nn: compute adaptive nearest neighbors
Categorical Search Initialization
These controls set categorical search starts and categorical direction-set initialization.
- dfac.dir
stretch factor for direction set search for Powell's algorithm for categorical variables. See Details
- dfac.init
non-random initial values for scale factors for categorical variables for Powell's algorithm. See Details
- hbd.dir
upper bound for direction set search for Powell's algorithm for categorical variables. See Details
- hbd.init
upper bound for scale factors for categorical variables for Powell's algorithm. See Details
- initd.dir
initial non-random values for direction set search for Powell's algorithm for categorical variables. See Details
- lbd.dir
lower bound for direction set search for Powell's algorithm for categorical variables. See Details
- lbd.init
lower bound for scale factors for categorical variables for Powell's algorithm. See Details
- scale.init.categorical.sample
a logical value that when set to
TRUEscaleslbd.dir,hbd.dir,dfac.dir, andinitd.dirby \(n^{-2/(2P+l)}\), \(n\) the number of observations, \(P\) the order of the kernel, and \(l\) the number ofnumericvariables. See Details
Continuous Direction-Set Search Controls
These controls set Powell direction-set initialization for continuous variables.
- cfac.dir
stretch factor for direction set search for Powell's algorithm for
numericvariables. See Details- dfc.dir
chi-square degrees of freedom for direction set search for Powell's algorithm for
numericvariables. See Details- initc.dir
initial non-random values for direction set search for Powell's algorithm for
numericvariables. See Details- lbc.dir
lower bound for direction set search for Powell's algorithm for
numericvariables. See Details
Continuous Kernel Support Controls
These controls choose and parameterize bounded support for continuous kernels.
- ckerbound
character string controlling continuous-kernel support handling. Can be set as
none(default kernel on full support),range(use sample min/max), orfixed(useckerlb/ckerub). The bounded-kernel route reuses the selected continuous kernel and renormalizes it on the chosen support; seenp.kernels.- ckerlb
numeric scalar/vector of lower bounds for continuous variables used when
ckerbound="fixed". Must satisfy lower-bound validity for each continuous variable (e.g.,<= min(variable)). Use-Inffor unbounded below. Seenp.kernelsfor bounded-kernel normalization details.- ckerub
numeric scalar/vector of upper bounds for continuous variables used when
ckerbound="fixed". Must satisfy upper-bound validity for each continuous variable (e.g.,>= max(variable)). UseInffor unbounded above. Seenp.kernelsfor bounded-kernel normalization details.
Continuous Scale-Factor Search Initialization
These controls define deterministic and random continuous scale-factor starts and the lower admissibility floor for fixed-bandwidth search.
- scale.factor.init
deterministic initial scale factor for continuous fixed-bandwidth search. Defaults to
0.5. The value supplied by the user is not rewritten, but the effective first start passed to the optimizer ismax(scale.factor.init, scale.factor.search.lower). See Details.- scale.factor.init.lower
lower endpoint for random continuous scale-factor starts. Defaults to
0.1. The value supplied by the user is not rewritten, but the effective random-start lower endpoint ismax(scale.factor.init.lower, scale.factor.search.lower). See Details.- scale.factor.init.upper
upper endpoint for random continuous scale-factor starts. Defaults to
2.0. It must be greater than or equal to the effective lower endpoint,max(scale.factor.init.lower, scale.factor.search.lower); otherwise bandwidth search errors rather than silently expanding the interval. See Details.- scale.factor.search.lower
optional nonnegative scalar giving the hard lower admissibility bound for continuous fixed-bandwidth search candidates. Defaults to
NULL. IfNULL, an existing bandwidth object's stored value is inherited when available; otherwise the package default0.1is used. This floor applies to computed/search bandwidth candidates and to effective search starts only. It does not rewrite explicit bandwidths supplied for storage withbandwidth.compute = FALSE. Final fixed-bandwidth search candidates must also have a finite valid raw objective value.
Distribution Integral And Grid Controls
These controls tune the distribution-function integral and grid calculations.
- do.full.integral
a logical value which when set as
TRUEevaluates the moment-based integral on the entire sample. Defaults toFALSE.- memfac
The algorithm to compute the least-squares objective function uses a block-based algorithm to eliminate or minimize redundant kernel evaluations. Due to memory, hardware and software constraints, a maximum block size must be imposed by the algorithm. This block size is roughly equal to memfac*10^5 elements. Empirical tests on modern hardware find that a memfac of 500 performs well. If you experience out of memory errors, or strange behaviour for large data sets (>100k elements) setting memfac to a lower value may fix the problem.
- ngrid
integer number of grid points to use when computing the moment-based integral. Defaults to
100.
- ckerorder
numeric value specifying kernel order (one of
(2,4,6,8)). Kernel order specified along with auniformcontinuous kernel type will be ignored. Defaults to2.- ckertype
character string used to specify the continuous kernel type. Can be set as
gaussian,epanechnikov, oruniform. Defaults togaussian.- okertype
character string used to specify the ordered categorical kernel type. Can be set as
wangvanryzin,liracine, orracineliyan. Defaults toliracine.
Numerical Search And Tolerance Controls
These controls set optimizer tolerances, restart behavior, invalid-candidate penalties, and bounded search transformations.
- ftol
fractional tolerance on the value of the cross-validation function evaluated at located minima (of order the machine precision or perhaps slightly larger so as not to be diddled by roundoff). Defaults to
1.490116e-07(1.0e+01*sqrt(.Machine$double.eps)).- invalid.penalty
a character string specifying the penalty used when the optimizer encounters invalid bandwidths.
"baseline"returns a finite penalty based on a baseline objective;"dbmax"returnsDBL\_MAX. Defaults to"baseline".- itmax
integer number of iterations before failure in the numerical optimization routine. Defaults to
10000.- nmulti
integer number of times to restart the process of finding extrema of the cross-validation function from different (random) initial points.
- penalty.multiplier
a numeric multiplier applied to the baseline penalty when
invalid.penalty="baseline". Defaults to10.- powell.remin
logical flag controlling Powell restart-from-minimum behavior. When
TRUE, the Powell-style search restarts from the located minimum for a minor gain in accuracy. Defaults toTRUE.- bwsolver
bandwidth optimizer for fixed-degree searches. The default
"powell"preserves the historical Powell route."mads"uses the native crs NOMAD C API over the bandwidth coordinates, and"mads+powell"applies one Powell hot start from the MADS solution. Advanced native NOMAD parameters may be supplied throughnomad.optsin...; invalid or unsupported parameters are rejected by NOMAD rather than silently ignored.- small
a small number used to bracket a minimum (it is hopeless to ask for a bracketing interval of width less than sqrt(epsilon) times its central value, a fractional width of only about 10-04 (single precision) or 3x10-8 (double precision)). Defaults to
small = 1.490116e-05 (1.0e+03*sqrt(.Machine$double.eps)).- tol
tolerance on the position of located minima of the cross-validation function (tol should generally be no smaller than the square root of your machine's floating point precision). Defaults to
1.490116e-04 (1.0e+04*sqrt(.Machine$double.eps)).- transform.bounds
a logical value that when set to
TRUEapplies an internal transformation that maps the unconstrained search to the feasible bandwidth domain. Defaults toFALSE.- eval.only
internal logical flag used by solver wrappers to evaluate an existing bandwidth candidate without running a bandwidth search. Ordinary users should leave this at its default
FALSE.
Details
The scale.factor.* controls are dimensionless search
controls. The package converts scale factors to bandwidths using the
estimator-specific scaling encoded in the bandwidth object, including
kernel order and the number of continuous variables relevant for the
estimator. Users should not pre-multiply these controls by sample-size
or standard-deviation factors.
scale.factor.init controls the deterministic first search
start. scale.factor.init.lower and
scale.factor.init.upper define the random multistart interval.
scale.factor.search.lower is the lower admissibility bound for
continuous fixed-bandwidth search candidates. The effective first
start is max(scale.factor.init, scale.factor.search.lower),
and the effective random-start lower endpoint is
max(scale.factor.init.lower, scale.factor.search.lower).
scale.factor.init.upper must be at least that effective lower
endpoint; the package errors rather than silently expanding the user's
interval.
When scale.factor.search.lower is NULL, an existing
bandwidth object's stored floor is inherited when available;
otherwise the package default 0.1 is used. Explicit bandwidths
supplied for storage with bandwidth.compute = FALSE are not
rewritten by the search floor.
Categorical search-start controls such as dfac.init,
lbd.init, and hbd.init have separate semantics and are
not affected by scale.factor.search.lower.
Documentation guide: see np.kernels for kernels,
np.options for global options, and
plot, plot.np for plotting options.
The bandwidth-selection argument surface is easiest to read by
decision group: data, grid, and existing bandwidth inputs; bandwidth
criterion and representation; continuous kernel and support controls
beginning with cker*; ordered categorical kernel controls
such as okertype; distribution-specific integral/grid controls
such as gdat, gdata, do.full.integral, and
ngrid; and numerical search initialization, tolerances, and
feasibility controls. Users who call npudist without a
bandwidth object can pass these same bandwidth-selection controls
through that function's ....
For S3 plotting help, see plot.np. You can list
available plot methods with methods("plot").
Typical usages are (see below for a complete list of options and also the examples at the end of this help file)
Usage 1: compute a bandwidth object using the formula interface:
bw <- npudistbw(~y)
Usage 2: compute a bandwidth object using the data frame interface
and change the default kernel and order:
Fhat <- npudistbw(tdat = y, ckertype="epanechnikov", ckerorder=4)
npudistbw implements a variety of methods for choosing
bandwidths for multivariate (\(p\)-variate) distributions defined
over a set of possibly continuous and/or discrete (ordered) data. The
approach is based on Li and Racine (2003) who employ
‘generalized product kernels’ that admit a mix of continuous
and discrete data types.
The cross-validation methods employ multivariate numerical search algorithms (direction set (Powell's) methods in multidimensions).
Bandwidths can (and will) differ for each variable which is, of course, desirable.
Three classes of kernel estimators for the continuous data types are available: fixed, adaptive nearest-neighbor, and generalized nearest-neighbor. Adaptive nearest-neighbor bandwidths change with each sample realization in the set, \(x_i\), when estimating the cumulative distribution at the point \(x\). Generalized nearest-neighbor bandwidths change with the point at which the cumulative distribution is estimated, \(x\). Fixed bandwidths are constant over the support of \(x\).
npudistbw may be invoked either with a formula-like
symbolic description of variables on which bandwidth selection is to
be performed or through a simpler interface whereby data is
passed directly to the function via the dat parameter. Use of
these two interfaces is mutually exclusive.
Data contained in the data frame dat may be a mix of continuous
(default) and ordered discrete (to be specified in the data frame
dat using ordered). Data can be entered in an
arbitrary order and data types will be detected automatically by the
routine (see np for details).
Data for which bandwidths are to be estimated may be specified
symbolically. A typical description has the form ~ data, where
data is a series of variables specified by name, separated by
the separation character '+'. For example, ~ x + y specifies
that the bandwidths for the joint distribution of variables x
and y are to be estimated. See below for further examples.
A variety of kernels may be specified by the user. Kernels implemented for continuous data types include the second, fourth, sixth, and eighth-order Gaussian and Epanechnikov kernels, and the uniform kernel. Ordered data types use a variation of the Wang and van Ryzin (1981) kernel.
The optimizer invoked for search is Powell's conjugate direction
method which requires the setting of (non-random) initial values and
search directions for bandwidths, and when restarting, random values
for successive invocations. Bandwidths for numeric variables
are scaled by robust measures of spread, the sample size, and the
number of numeric variables where appropriate. Two sets of
parameters for bandwidths for numeric can be modified, those
for initial values for the parameters themselves, and those for the
directions taken (Powell's algorithm does not involve explicit
computation of the function's gradient). The default values are set by
considering search performance for a variety of difficult test cases
and simulated cases. We highly recommend restarting search a large
number of times to avoid the presence of local minima (achieved by
modifying nmulti). Further refinement for difficult cases can
be achieved by modifying these sets of parameters. However, these
parameters are intended more for the authors of the package to enable
‘tuning’ for various methods rather than for the user them
self.
Value
npudistbw returns a bandwidth object with the
following components:
- bw
bandwidth(s), scale factor(s) or nearest neighbours for the data,
dat- fval
objective function value at minimum
if bwtype is set to fixed, an object containing
bandwidths, of class bandwidth
(or scale factors if bwscaling = TRUE) is returned. If it is set to
generalized_nn or adaptive_nn, then instead the
\(k\)th nearest
neighbors are returned for the continuous variables while the discrete
kernel bandwidths are returned for the discrete variables. Bandwidths
are stored under the component name bw, with each
element \(i\) corresponding to column \(i\) of input data
dat.
The functions predict, summary and plot support
objects of type bandwidth.
Book And Method Pointers
npudistbw selects bandwidths for the unconditional distribution
target \(F(x)=\Pr(X\le x)\) estimated by npudist.
The selected bandwidths control the integrated kernel factors used in
the mixed-data CDF estimator.
For book-length derivations, see Li and Racine (2007), Chapter 1 Density Estimation, especially Sections 1.4 and 1.5, and Chapter 4 Kernel Estimation with Mixed Data. The later workflow treatment is Racine (2019), Chapters 2 and 3.
References
Aitchison, J. and C.G.G. Aitken (1976), “Multivariate binary discrimination by the kernel method,” Biometrika, 63, 413-420.
Bowman, A. and P. Hall and T. Prvan (1998), “Bandwidth selection for the smoothing of distribution functions,” Biometrika, 85, 799-808.
Li, Q. and J.S. Racine (2007), Nonparametric Econometrics: Theory and Practice, Princeton University Press.
Li, Q. and J.S. Racine (2003), “Nonparametric estimation of distributions with categorical and continuous data,” Journal of Multivariate Analysis, 86, 266-292.
Li, C. and H. Li and J.S. Racine (2017), “Cross-Validated Mixed Datatype Bandwidth Selection for Nonparametric Cumulative Distribution/Survivor Functions,” Econometric Reviews, 36, 970-987.
Ouyang, D. and Q. Li and J.S. Racine (2006), “Cross-validation and the estimation of probability distributions with categorical data,” Journal of Nonparametric Statistics, 18, 69-100.
Pagan, A. and A. Ullah (1999), Nonparametric Econometrics, Cambridge University Press.
Scott, D.W. (1992), Multivariate Cumulative Distribution Estimation: Theory, Practice and Visualization, New York: Wiley.
Silverman, B.W. (1986), Density Estimation, London: Chapman and Hall.
Wang, M.C. and J. van Ryzin (1981), “A class of smooth estimators for discrete distributions,” Biometrika, 68, 301-309.
Author
Tristen Hayfield tristen.hayfield@gmail.com, Jeffrey S. Racine racinej@mcmaster.ca
Usage Issues
If you are using data of mixed types, then it is advisable to use the
data.frame function to construct your input data and not
cbind, since cbind will typically not work as
intended on mixed data types and will coerce the data to the same
type.
Caution: multivariate data-driven bandwidth selection methods are, by
their nature, computationally intensive. Virtually all methods
require dropping the \(i\)th observation from the data set, computing an
object, repeating this for all observations in the sample, then
averaging each of these leave-one-out estimates for a given
value of the bandwidth vector, and only then repeating this a large
number of times in order to conduct multivariate numerical
minimization/maximization. Furthermore, due to the potential for local
minima/maxima, restarting this procedure a large number of times may
often be necessary. This can be frustrating for users possessing
large datasets. For exploratory purposes, you may wish to override the
default search tolerances, say, setting ftol=.01 and tol=.01 and
conduct multistarting (the default is to restart min(2, ncol(dat))
times) as is done for a number of examples. Once the procedure
terminates, you can restart search with default tolerances using those
bandwidths obtained from the less rigorous search (i.e., set
bws=bw on subsequent calls to this routine where bw is
the initial bandwidth object). A version of this package using the
Rmpi wrapper is under development that allows one to deploy
this software in a clustered computing environment to facilitate
computation involving large datasets.
See also
np.kernels, np.options, plot, plot.np
bw.nrd, bw.SJ, hist,
npudist, npudist
Examples
if (FALSE) { # \dontrun{
# EXAMPLE 1 (INTERFACE=FORMULA): For this example, we load Giovanni
# Baiocchi's Italian GDP panel (see Italy for details), then create a
# data frame in which year is an ordered factor, GDP is continuous.
data("Italy")
with(Italy, {
data <- data.frame(ordered(year), gdp)
# We compute bandwidths for the kernel cumulative distribution estimator
# using the normal-reference rule-of-thumb. Otherwise, we use the
# defaults (second order Gaussian kernel, fixed bandwidths). Note that
# the bandwidth object you compute inherits all properties of the
# estimator (kernel type, kernel order, estimation method) and can be
# fed directly into the plotting utility plot() or into the npudist()
# function.
bw <- npudistbw(formula=~ordered(year)+gdp, bwmethod="normal-reference")
summary(bw)
# Sleep for 5 seconds so that we can examine the output...
if (interactive()) Sys.sleep(5)
# Next, specify a value for the bandwidths manually (0.5 for the first
# variable, 1.0 for the second)...
bw <- npudistbw(formula=~ordered(year)+gdp, bws=c(0.5, 1.0),
bandwidth.compute=FALSE)
summary(bw)
# Sleep for 5 seconds so that we can examine the output...
if (interactive()) Sys.sleep(5)
# Next, if you wanted to use the 1.587 sigma n^{-1/(2p+q)} rule-of-thumb
# for the bandwidth for the continuous variable and, say, no smoothing
# for the discrete variable, you would use the bwscaling=TRUE argument
# and feed in the values 0 for the first variable (year) and 1.587 for
# the second (gdp). Note that in the printout it reports the `scale
# factors' rather than the `bandwidth' as reported in some of the
# previous examples.
bw <- npudistbw(formula=~ordered(year)+gdp, bws=c(0, 1.587),
bwscaling=TRUE,
bandwidth.compute=FALSE)
summary(bw)
# Sleep for 5 seconds so that we can examine the output...
if (interactive()) Sys.sleep(5)
# If you wished to use, say, an eighth-order Epanechnikov kernel for the
# continuous variables and specify your own bandwidths, you could do
# that as follows.
bw <- npudistbw(formula=~ordered(year)+gdp, bws=c(0.5, 1.0),
bandwidth.compute=FALSE,
ckertype="epanechnikov",
ckerorder=8)
summary(bw)
# Sleep for 5 seconds so that we can examine the output...
if (interactive()) Sys.sleep(5)
# If you preferred, say, nearest-neighbor bandwidths and a generalized
# kernel estimator for the continuous variable, you would use the
# bwtype="generalized_nn" argument.
bw <- npudistbw(formula=~ordered(year)+gdp, bwtype = "generalized_nn")
summary(bw)
# Sleep for 5 seconds so that we can examine the output...
if (interactive()) Sys.sleep(5)
# Next, compute bandwidths using cross-validation, fixed bandwidths, and
# a second-order Gaussian kernel for the continuous variable (default).
# Note - this may take a few minutes depending on the speed of your
# computer.
bw <- npudistbw(formula=~ordered(year)+gdp)
summary(bw)
# Sleep for 5 seconds so that we can examine the output...
if (interactive()) Sys.sleep(5)
# Finally, if you wish to use initial values for numerical search, you
# can either provide a vector of bandwidths as in bws=c(...) or a
# bandwidth object from a previous run, as in
bw <- npudistbw(formula=~ordered(year)+gdp, bws=c(1, 1))
summary(bw)
})
# EXAMPLE 1 (INTERFACE=DATA FRAME): For this example, we load Giovanni
# Baiocchi's Italian GDP panel (see Italy for details), then create a
# data frame in which year is an ordered factor, GDP is continuous.
data("Italy")
with(Italy, {
data <- data.frame(ordered(year), gdp)
# We compute bandwidths for the kernel cumulative distribution estimator
# using the normal-reference rule-of-thumb. Otherwise, we use the
# defaults (second-order Gaussian kernel, fixed bandwidths). Note that
# the bandwidth object you compute inherits all properties of the
# estimator (kernel type, kernel order, estimation method) and can be
# fed directly into the plotting utility plot() or into the npudist()
# function.
bw <- npudistbw(dat=data, bwmethod="normal-reference")
summary(bw)
# Sleep for 5 seconds so that we can examine the output...
if (interactive()) Sys.sleep(5)
# Next, specify a value for the bandwidths manually (0.5 for the first
# variable, 1.0 for the second)...
bw <- npudistbw(dat=data, bws=c(0.5, 1.0), bandwidth.compute=FALSE)
summary(bw)
# Sleep for 5 seconds so that we can examine the output...
if (interactive()) Sys.sleep(5)
# Next, if you wanted to use the 1.587 sigma n^{-1/(2p+q)} rule-of-thumb
# for the bandwidth for the continuous variable and, say, no smoothing
# for the discrete variable, you would use the bwscaling=TRUE argument
# and feed in the values 0 for the first variable (year) and 1.587 for
# the second (gdp). Note that in the printout it reports the `scale
# factors' rather than the `bandwidth' as reported in some of the
# previous examples.
bw <- npudistbw(dat=data, bws=c(0, 1.587),
bwscaling=TRUE,
bandwidth.compute=FALSE)
summary(bw)
# Sleep for 5 seconds so that we can examine the output...
if (interactive()) Sys.sleep(5)
# If you wished to use, say, an eighth-order Epanechnikov kernel for the
# continuous variables and specify your own bandwidths, you could do
# that as follows:
bw <- npudistbw(dat=data, bws=c(0.5, 1.0),
bandwidth.compute=FALSE,
ckertype="epanechnikov",
ckerorder=8)
summary(bw)
# Sleep for 5 seconds so that we can examine the output...
if (interactive()) Sys.sleep(5)
# If you preferred, say, nearest-neighbor bandwidths and a generalized
# kernel estimator for the continuous variable, you would use the
# bwtype="generalized_nn" argument.
bw <- npudistbw(dat=data, bwtype = "generalized_nn")
summary(bw)
# Sleep for 5 seconds so that we can examine the output...
if (interactive()) Sys.sleep(5)
# Next, compute bandwidths using cross-validation, fixed bandwidths, and
# a second order Gaussian kernel for the continuous variable (default).
# Note - this may take a few minutes depending on the speed of your
# computer.
bw <- npudistbw(dat=data)
summary(bw)
# Sleep for 5 seconds so that we can examine the output...
if (interactive()) Sys.sleep(5)
# Finally, if you wish to use initial values for numerical search, you
# can either provide a vector of bandwidths as in bws=c(...) or a
# bandwidth object from a previous run, as in
bw <- npudistbw(dat=data, bws=c(1, 1))
summary(bw)
})
} # }