Query on ksmooth(): Theoretical step function vs. plotted diagonal segments

송상은 <[email protected]> Thu, 19 Mar 2026 23:00:00 +0900
Newsgroups gmane.comp.lang.r.general
Message-ID <CA+3fqOpX-XK4L9VyNUz9h9Eeh=3w2cFM-E3_Ue=AbL7GsdX43w@mail.gmail.com>
Dear R-help members,

Hello,
I am studying kernel regression and experimenting with the ksmooth()
function in R.

When using a box kernel, the kernel function is an indicator function
(weight = 1 inside the bandwidth and 0 outside). Based on this definition,
I expected the Nadaraya–Watson estimator to produce a step-like function:
the estimate should remain constant while the set of included points is
unchanged, and then jump when a point enters or leaves the bandwidth window.

However, when I run the following code using the cars dataset:

par(mfrow=c(1,1))
with(cars, {
plot(speed, dist)
lines(ksmooth(speed, dist, "normal", bandwidth = 2),
col = "blue", lwd = 3)
lines(ksmooth(speed, dist, "box", bandwidth = 2),
col = "darkorange", lwd = 3)
})
legend("topleft", c("Normal Kernel with h=2", "Box Kernel with h=2"),
lwd = c(2,2),
col = c("blue","darkorange"), cex = 2)

the curve produced by the box kernel (dark orange) appears to contain
diagonal line segments rather than the step-like shape I expected. I have
attached the resulting plot for reference.

My understanding is that the theoretical estimator should behave like a
step function because the kernel weights are either 0 or 1. Therefore, I
was wondering whether the diagonal segments arise from how ksmooth()
evaluates the estimator on a grid of x values and then connects those
points with straight lines for plotting, or if there is another
implementation detail that explains this behavior.

Could you please clarify whether this is expected behavior?

Thank you very much for your time.

Best regards,
Sangeun Song
plot_ksmooth_box.png (image/png, 163.4 KB) - not displayed