Saul Garcia Saul Garcia - 9 months ago 59
R Question

Understanding the Local Polynomial Regression

Could someone explain me why I get different lines when I plot? Somehow I thought the line should be the same


lgWeight <- log(Weight)


# a) Fit a nonparametric regression to data (xi,yi) and save the estimated values mˆ (xi).

# Regression of degree 2 polynomial of lgWeight against Yr
op <- par(mfrow=c(2,1))
lpr1 <- locpoly(Yr,lgWeight, bandwidth=7, degree = 2, gridsize = length(Yr))
plot(Yr,lgWeight,col="grey", ylab="Log(Weight)", xlab = "Year")
lines(lpr1,lwd=2, col="blue")
lines(lpr1$y, col="black")

enter image description here

How can I get the values from the model? If I print the model, it gives me the values on
, but somehow if I plot them, is not the same as the blue line. I need the values of the fitted model (blue) for every
, could someone help me?

Answer Source

The fitted model (blue curve) is correctly in lpr1. As you said, the correct y-values are in lpr1$y and the correct x-values are in lpr1$x.

The reason the second plot looks like a straight line is because you are only giving the plot function one variable, lpr1$y. Since you don't specify the x-coordinates, R will automatically plot them along an index, from 1 to the length of the y variable.

The following are two explicit and equivalent ways to plot the curve and line:

lines(x = lpr1$x, y = lpr1$y,lwd=2, col="blue")  # plots curve
lines(x = 1:length(lpr1$y), y = lpr1$y, col="black")  # plot line