library(faraway)

### Data of the three examples
par(mfrow=c(1,3))
data(exa)
plot (y ~ x, exa,main="Example A")
lines(m ~ x, exa)
data(exb)
plot(y ~ x, exb,main="Example B")
lines(m ~ x, exb)
data(faithful)
plot(waiting ~ eruptions, faithful,main="old Faithful")

### kernel smoother with different bandwidths
par(mfrow=c(1,3))
plot(waiting ~ eruptions,
faithful,main="bandwidth=0.1", col="gray", cex=0.5)
lines(ksmooth(faithful$eruptions,faithful$waiting,"normal",0.1), lwd=2)

plot(waiting ~ eruptions,faithful,main="bandwidth=0.5", col="gray", cex=0.5)
lines(ksmooth(faithful$eruptions,faithful$waiting,"normal",0.5), lwd=2)

plot(waiting ~ eruptions, faithful,main="bandwidth=2", col="gray", cex=0.5)
lines(ksmooth(faithful$eruptions,faithful$waiting,"normal", 2),lwd=2)

### Use CV to select bandwidth
library(sm)
par(mfrow=c(1,2))
hm = hcv(faithful$eruptions,faithful$waiting,display="lines")
sm.regression(faithful$eruptions,faithful$waiting,h=hm, xlab="duration",ylab="waiting")
par(mfrow=c(1,2))
hm=hcv(exa$x,exa$y,display="lines")
sm.regression(exa$x,exa$y,h=hm,xlab="x",ylab="y")
par(mfrow=c(1,2))
hm = hcv(exb$x,exb$y,display="lines",hstart=0.005)
sm.regression(exb$x,exb$y,h=0.005)

### Smoothing splines

par(mfrow=c(1,3))
plot(waiting ~ eruptions, faithful,col="gray", cex=0.5)
lines(smooth.spline(faithful$eruptions,faithful$waiting), lwd=1.5, col="red")

plot(y ~ x, exa,col="gray", cex=0.5)
lines(exa$x,exa$m)
lines(smooth.spline(exa$x,exa$y),lty=2, lwd=1.5, col="red")
plot(y ~ x, exb, col="gray", cex=0.5)
lines(exb$x,exb$m)
lines(smooth.spline(exb$x,exb$y), lty=2, lwd=1.5, col="red")

### Loess
?loess

par(mfrow=c(1,3))
plot(waiting ~ eruptions, faithful,col="gray", cex=0.5)
f=loess(waiting ~ eruptions, faithful)
i = order(faithful$eruptions)
lines(f$x[i],f$fitted[i], lwd=1.5, col="red")

plot(y ~ x, exa, col="gray", cex=0.5)
lines(exa$x,exa$m,lty=1)
f = loess(y ~ x,exa)
lines(f$x,f$fitted,lty=2, lwd=1.5, col="red")
f = loess(y ~ x, exa, span=0.22)
lines(f$x,f$fitted,lty=5, lwd=1.5, col="blue")

plot(y ~ x, exb, col="gray", cex=0.5)
lines(exb$x,exb$m, lty=1)
f =loess(y ~ x, exb)
lines(f$x,f$fitted,lty=2,lwd=1.5, col="red")
f = loess(y ~ x, exb,span=1)
lines(f$x,f$fitted,lty=5, lwd=1.5, col="blue")