Saul Garcia - 2 months ago 31

R Question

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

`data(aircraft)`

help(aircraft)

attach(aircraft)

lgWeight <- log(Weight)

library(KernSmooth)

# 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")

How can I get the values from the model? If I print the model, it gives me the values on

`$x`

`$y`

`x`

Answer

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
```