# Locally constant fit near the top edge of the data
x <- 15 # design point
h <- 3.5 # window [11.5, 18.5] holds schooling levels 12 to 16
# The window runs past the most schooling anyone has, 16 years.
k_weights <- dunif( abs(xy_hat[, 'x_hat']-x)/h, -1, 1) # the uniform kernel k_U
xy_window <- xy_hat[k_weights > 0, ]
m_x <- mean(xy_window[, 'x_hat']) # average schooling in the window
m_y <- mean(xy_window[, 'y_hat']) # locally constant fit at x=15
c(m_x=m_x, m_y=m_y)
## m_x m_y
## 12.686759 6.291988
# About 92 percent of workers in the window have under 15 years of schooling.
# So the window mean describes a group averaging about 12.7 years, not 15.
# A line fit to the same window, evaluated at the design point
reg_window <- lm(y_hat ~ x_hat, data=xy_window)
y_pred_line <- predict(reg_window, newdata=data.frame(x_hat=x))
y_pred_line
## 1
## 8.244139
# The line follows the trend out to x=15, where it predicts about 8.24.
# Grouped mean wage at the design point
y_grp <- school_means[school_means[, 'x_hat'] == x, 'y_hat']
y_grp
## [1] 8.375111
# The window mean, about 6.29, sits far below the grouped mean of 8.38.
# Wages rise with schooling.
# So the window mean understates the mean wage at x=15.
# Plot the window
plot(y_hat ~ x_hat, data=xy_window, pch=16, col=grey(0, .1),
ylim=c(0, 15), # zoom in on the fits
main=NA, xlab='School', ylab='Wage')
abline(h=m_y, col=rgb(0, 0, 1, .8), lwd=2) # window mean
lines(c(12, 16), predict(reg_window, newdata=data.frame(x_hat=c(12, 16))),
col=rgb(1, 0, 0, .8), lwd=2) # window line
points(m_x, m_y, pch=16, col=rgb(0, 0, 0, .8), cex=1.5) # window center
points(c(x, x), c(m_y, y_pred_line), pch=16, cex=1.5,
col=c(rgb(0, 0, 1, .8), rgb(1, 0, 0, .8))) # the two fits at x=15
points(y_hat ~ x_hat, data=school_means, pch=24, col='white', bg=rgb(0, 0, 0, .8), cex=1.3) # grouped means
abline(v=x, col=grey(.5), lty=3)
legend('topleft',
legend=c('Window mean', 'Window line', 'Window center', 'Grouped mean'),
col=c(rgb(0, 0, 1, .8), rgb(1, 0, 0, .8), rgb(0, 0, 0, .8), 'white'),
lty=c(1, 1, NA, NA), pch=c(NA, NA, 16, 24), lwd=2, pt.bg=rgb(0, 0, 0, .8), cex=.8, bg='white')