Start Here
Gallery of code for np, npRmpi, and crs
This site is meant to help you get to working code quickly. Use the sidebar to browse by task, or search directly for function names such as npreg, npudens, crs, and npRmpi.init.
This gallery complements the package help pages, examples, and vignettes. The aim is simple: make it easy to see what each package is for, copy a small working example, and then move on to longer scripts only if you need them.
If you are new to these packages, start with Choose a Package. If you want runnable code immediately, go to Quickstarts. If you already know the method you want, go directly to Kernel Methods, MPI and Large Data, Splines, or Worked Examples.
This website is a practical working companion to the package manuals and the underlying papers, not a substitute for them.
New to np? Watch Your first np result, a half-minute RStudio demonstration, then continue with the copyable script.
crs 0.15-46 (published August 19, 2026), npRmpi 0.80-2, and np 0.80-2 are available on CRAN. The np and npRmpi releases are dated November 13, 2026.
The examples use current estimator controls such as B, se, se.fit, and gradient.order, together with plot controls such as errors, bootstrap, band, data_rug, and data_overlay. The 0.80-2 migration checklist summarizes the argument changes most likely to affect older code.
Explore a conditional distribution
Italian regional GDP distribution and median, 1951–2024
This surface estimates F(gdp | year) across Italy's 20 regions, with real GDP per capita measured in thousands of 2020 euros. The grey curve traces the conditional median and its floor projection; the 3D rug marks the observed year–GDP support. The opening view makes the projection readable as a familiar two-dimensional curve.
What is being estimated?
npcdist() estimates the conditional distribution with year treated as an ordered factor. npqreg() inverts it: \(Q_\tau(\mathrm{year}) = F^{-1}(\tau \mid \mathrm{year})\). At tau = 0.5, this is the conditional median. Reusing Fhat$bws avoids another bandwidth search. The grey traces show the same quantile at F = tau and on the floor at F = 0; the 3D rug marks the observed support. The opening angle emphasizes the floor projection, while rotation reveals its relationship to the surface. The panel combines a historical SVIMEZ reconstruction with modern ARDECO regional data.
The expanded data are included with np 0.80-3. Download the R script, or expand the example below.
## Load the package and updated Italian regional panel
library(np)
# This example requires the suggested rgl package: install.packages("rgl")
data("Italy_Updated")
# gdp is real GDP per capita in thousands of 2020 euros.
# With np < 0.80-3, use data("Italy") and data = Italy below.
# np 0.80-2 requires the snake-case spelling data_rug = TRUE.
## Estimate F(gdp | year), then face its floor projection toward the viewer
Fhat <- npcdist(gdp ~ year, data = Italy_Updated)
widget <- plot(Fhat, renderer = "rgl", zlab = "F(gdp|year)",
theta = 300, phi = 10, data.rug = TRUE)
## Reuse its bandwidths to estimate a conditional quantile without a new search
tau <- 0.5 # Use 0.25 for the conditional first quartile, and so forth.
Qhat <- npqreg(bws = Fhat$bws, tau = tau, data = Italy_Updated)
# Optional: plot(Qhat) draws the conditional quantile.
# plot(Qhat, gradients = TRUE) draws its marginal effect, \Delta Q / \Delta year.
year_grid <- data.frame(
year = ordered(levels(Italy_Updated$year),
levels = levels(Italy_Updated$year)))
year_num <- as.numeric(as.character(year_grid$year))
cond_quantile <- drop(predict(Qhat, newdata = year_grid))
## Trace the selected quantile at F = tau and project it onto the floor
rgl::plot3d(widget)
rgl::lines3d(year_num, cond_quantile, 0, color = "grey45", lwd = 1.5)
rgl::lines3d(year_num, cond_quantile, tau, color = "grey45", lwd = 1)
rgl::rglwidget()The first panel below estimates each year’s CDF separately, including a separate GDP bandwidth. The second remains cell-based by fixing the ordered year bandwidth at lambda = 0, but selects one common GDP bandwidth across years. The final npcdist() fit also borrows strength across the ordered year axis. Comparing all three separates the effect of a common bandwidth from the additional smoothing supplied by neighboring years. With only 20 regions per year, the joint fit produces a markedly steadier year-to-year CDF and median path than independent annual fits in this example.
## Load the data and define a common evaluation grid
# This comparison requires the suggested rgl package: install.packages("rgl")
options(rgl.useNULL = TRUE) # Avoid native OpenGL warnings for HTML widgets.
library(np)
data("Italy_Updated")
set.seed(20261114)
years <- levels(Italy_Updated$year)
year_num <- as.numeric(years)
gdp_grid <- seq(0, ceiling(max(Italy_Updated$gdp) * 1.05),
length.out = 121)
tau <- 0.5
## Estimate each year's CDF and median using its own selected bandwidth
annual_fit <- lapply(years, function(yr) {
annual_data <- droplevels(
Italy_Updated[Italy_Updated$year == yr, , drop = FALSE])
bw <- npudistbw(~gdp, data = annual_data, nmulti = 1)
Fhat <- npudist(bws = bw, newdata = data.frame(gdp = gdp_grid))
list(
cdf = fitted(Fhat),
quantile = npquantile(annual_data$gdp, tau = tau, bws = bw))
})
cdf_separate <- do.call(rbind, lapply(annual_fit, `[[`, "cdf"))
quantile_separate <- vapply(annual_fit,
function(fit) unname(fit$quantile), numeric(1))
## Assemble a common year-by-GDP evaluation grid
eval_grid <- expand.grid(
year = ordered(years, levels = years),
gdp = gdp_grid,
KEEP.OUT.ATTRS = FALSE)
year_grid <- data.frame(year = ordered(years, levels = years))
evaluate_conditional_fit <- function(bws) {
Fhat <- npcdist(bws = bws, newdata = eval_grid)
Qhat <- npqreg(bws = bws, tau = tau, data = Italy_Updated)
list(
cdf = matrix(fitted(Fhat), nrow = length(years)),
quantile = drop(predict(Qhat, newdata = year_grid)))
}
## Select one GDP bandwidth while retaining cell-based year estimates
bw_common <- npcdistbw(gdp ~ year, data = Italy_Updated, nmulti = 1,
lbd.dir = 0, hbd.dir = 0, dfac.dir = 0, initd.dir = 0,
lbd.init = 0, hbd.init = 0, dfac.init = 0)
stopifnot(as.numeric(bw_common$xbw) == 0)
common_fit <- evaluate_conditional_fit(bw_common)
## Jointly select the GDP and ordered-year bandwidths
joint_model <- npcdist(gdp ~ year, data = Italy_Updated)
joint_fit <- evaluate_conditional_fit(joint_model$bws)
## Use np's viridis surface palette and its small RGL boundary clearance
palette <- grDevices::hcl.colors(1000, palette = "viridis")
cdf_limits <- grDevices::extendrange(c(0, 1), f = 0.001)
surface_colors <- function(cdf) {
index <- 1 + floor(999 * pmax(0, pmin(1, cdf)))
matrix(palette[index], nrow = nrow(cdf), ncol = ncol(cdf))
}
draw_panel <- function(cdf, quantile, title) {
rgl::persp3d(year_num, gdp_grid, cdf, zlim = cdf_limits,
xlab = "year",
ylab = "real GDP per capita (thousands of 2020 euros)",
zlab = "F(gdp|year)", main = title, ticktype = "detailed",
color = surface_colors(cdf), alpha = 0.6, back = "lines",
border = palette[32], lit = FALSE)
rgl::points3d(as.numeric(as.character(Italy_Updated$year)),
Italy_Updated$gdp, 0, color = "grey55", alpha = 0.35, size = 2)
rgl::lines3d(year_num, quantile, tau, color = "grey30", lwd = 1)
rgl::lines3d(year_num, quantile, 0, color = "grey30", lwd = 1.5)
rgl::grid3d(c("x", "y+", "z"), col = "grey", lwd = 1)
rgl::view3d(theta = 300, phi = 10, fov = 55)
}
## Draw synchronized panels that rotate and zoom together
rgl::open3d(useNULL = TRUE, silent = TRUE)
rgl::mfrow3d(1, 3, sharedMouse = TRUE)
draw_panel(cdf_separate, quantile_separate,
"Separate bandwidth per year")
rgl::next3d()
draw_panel(common_fit$cdf, common_fit$quantile,
"Common GDP bandwidth, lambda = 0")
rgl::next3d()
draw_panel(joint_fit$cdf, joint_fit$quantile,
"Ordered-year-smoothed npcdist")
rgl::rglwidget(width = 2100, height = 720)Current Capabilities
- 0.80-2 update and migration notes:
npandnpRmpi0.80-2use snake_case compound plot controls and a commonnp_plot_datareturn schema; enforce numeric responses across the regression family; refine plot-grid semantics; extend bounded-density plotting and interval support; and strengthen formula evaluation, RNG replay, and MPI startup and ownership checks. - Spline updates:
crs0.15-46retains the common named plotting controls andcrshat()operator workflow, adds formula/data and S3 support for instrumental spline regression, and provides the observed NOMAD interface used for responsive progress in downstream degree searches. - Local polynomial workflows:
npandnpRmpisupport local polynomial capability across the conditional family, with joint selection of polynomial degrees and bandwidths for mixed data, gradient support throughout the conditional estimators, and derivative estimation of arbitrarily high order, limited only by the selected polynomial degree whether set manually or chosen automatically for the underlying smoothness class. - Boundary-aware density estimation: unconditional and conditional density workflows support known two-sided or one-sided bounds and practical unknown-bound proxies, with a worked example showing what changes in finite- and unbounded-support settings.
- Location-scale quantile regression:
nplsqregandnplsqregbwprovide a first-class location-scale quantile workflow with formula and bandwidth-object routes, scalar or vectortau, stored-quantile selection throughpredict(..., tau = ...), residuals, summaries, plots, and the same NOMAD-enabled local-polynomial degree-and-bandwidth search style where supported. - Conditional quantile regression:
npqregprovides a direct formula interface, automaticnpcdistbw()bandwidth selection whenbwsis omitted, vectortausupport,plot(..., tau = ...)reuse of existing bandwidths, conditional-quantile gradients and standard errors, andnomad = "auto"pass-through for local-polynomial degree-and-bandwidth search. - Conditional mode classification:
npconmodeis a first-class high-level estimator, with direct formula/data/newdata workflows, automaticnpcdensbw()bandwidth selection whenbwsis omitted, conditional-density search controls includingnomad = "auto", mirrored degree/search metadata in returned objects and summaries, properized fitted class probabilities for non-local-constant routes before selecting the modal outcome, and level-specific class-probability effects. - Copula estimation:
npcopulais a first-class high-level estimator with a direct formula interface, automaticnpudistbw()ornpudensbw()selection whenbwsis omitted, automatic two-dimensional probability-grid construction for the default grid route, and easy reuse of the selected bandwidth object when you want a customugrid or copula-density target. - Hat-matrix and operator helpers:
npreghat,npindexhat,npplreghat, andnpscoefhatprovide one-call operator routes that simplify constrained nonparametric and semiparametric estimation by replacing much of the manual hat-matrix construction and solve-based setup, whilenpudenshat,npudisthat,npcdenshat, andnpcdisthatextend the same streamlined operator style to the density/distribution family. - Variability bounds on plots: pointwise, Bonferroni, and simultaneous bounds share the plotting surface across supported regression, density/distribution, quantile, class-probability, and copula targets, and
band = "all"presents all three together. - Interactive plotting surfaces:
renderer = "rgl"supports interactive 3D rotation/zoom whenrglis installed, whiledata_ruganddata_overlaycontrol rugs and observed-data overlays on supported routes. - MPI operational routes:
npRmpisession and attach routes let users work directly withnp-style code, while the profile route remains available when needed.
Choose a Package
Start here if you are deciding between np, npRmpi, and crs, or if you want a quick route to the right tool.
Install and Get Started
Short install notes, a minimal first run, and pointers for what to do next once the packages are installed.
Quickstarts
Small runnable scripts for np, npRmpi, and crs, shown inline so you can copy directly from the page.
Kernel Methods
Core workflows for np, together with a clean route to npRmpi when jobs become larger or more time consuming.
MPI and Large Data
Updated guidance for npRmpi, with session mode now treated as the main interactive path rather than an afterthought.
Worked Examples
Copyable code snippets on the page, plus links to longer scripts when you want the full commented version.
Multivariate Regression
Mixed-data regression, partial plots, and prediction using wage1 as a practical first multivariate example.
FAQ and Troubleshooting
Common questions, support routes, and links to the current canonical sources.
Learn by topic
Kernel Primer
Short conceptual introduction to mixed-data kernels, bandwidth objects, and the basic np workflow.
Density, Distribution, Quantiles
Route to npudens, npudist, npcdens, npcdist, and npqreg workflows.
Semiparametric Models
Partially linear, single-index, and varying-coefficient workflows in one place.
Entropy and Testing
Overview of the entropy-based testing procedures and a small “roll your own” example.
Classification and Modes
Nonparametric classification and conditional-mode workflows, including the birthwt example.
Build With npksum
For users who want to construct custom kernel objects or estimators rather than only use the higher-level wrappers.
Spline Primer
Conceptual introduction to regression splines, knots, basis functions, and how that connects to crs.
Code Catalog
Broader script library across np, npRmpi, and crs, including older scripts and fuller worked examples beyond the first quickstarts.
Need help fast?
FAQ and Troubleshooting
Short answers to the most common “where do I start?” and “why is this happening?” questions.
Data Preparation
Variable classes, factors, ordered variables, formulas, and the data-typing mistakes that most often trip people up.
Runtime and Scaling
What to do when cross-validation, bootstrap, spline search, or large jobs become slow or memory-hungry.
Spline Search and Tuning
Practical crs advice on search size, smoothness, knots, and when to narrow the spline search space.
Notes
- Search should help if you know the function name but not where it lives.
- Quickstarts is the shortest route to a small runnable script.
- The reference page groups functions by task rather than repeating a long handwritten index.
- Additional resources, including books and papers, are collected on Books, Papers, and Citation.
Feedback is welcome. My academic page is experts.mcmaster.ca/display/racinej, and additional materials remain available at jeffreyracine.github.io/research.