library(MASS)
data(mcycle)
# local means
m0<-Locmean(mcycle$accel, mcycle$times, span=.1)
m1<-Locmean(mcycle$accel, mcycle$times, span=.2)
m2<-Locmean(mcycle$accel, mcycle$times, span=.3)
span <- c("span=0.1", "span=0.2", "span=0.3")
plot(accel~times, data=mcycle,main="local mean")
lines(fitted(m0)~mcycle$times, col=1, lty=1)
lines(fitted(m1)~mcycle$times, col=2, lty=2)
lines(fitted(m2)~mcycle$times, col=3, lty=3)
legend(1.5,50, legend = span, col = 1:3,
lty = 1:3, cex = .8, y.intersp = 1)
# kernel estimation
k0<-WLocmean(mcycle$accel, mcycle$times, lambda=1)
k1<-WLocmean(mcycle$accel, mcycle$times, lambda=2)
k2<-WLocmean(mcycle$accel, mcycle$times, lambda=3)
lambda <- c("lambda=1", "lambda=2", "lambda=3")
plot(accel~times, data=mcycle,main="Gaussian kernel fit")
lines(fitted(k0)~mcycle$times, col=1, lty=1)
lines(fitted(k1)~mcycle$times, col=2, lty=2)
lines(fitted(k2)~mcycle$times, col=3, lty=3)
legend(1.5,50, legend = lambda, col = 1:3,
lty = 1:3, cex = .8, y.intersp = 1)
# local polymials
l1<-Locpoly(mcycle$accel, mcycle$times, span=.1)
l2<-Locpoly(mcycle$accel, mcycle$times, span=.2)
l3<-Locpoly(mcycle$accel, mcycle$times, span=.3)
span <- c("span=0.1", "span=0.2", "span=0.3")
plot(accel~times, data=mcycle,main="local linear fit")
lines(fitted(l1)~mcycle$times, col=1, lty=1)
lines(fitted(l2)~mcycle$times, col=2, lty=2)
lines(fitted(l2)~mcycle$times, col=3, lty=3)
legend(1.5,50, legend = span, col = 1:3,
lty = 1:3, cex = .8, y.intersp = 1)
# weighted local polynomials
lw1<-WLocpoly(mcycle$accel, mcycle$times, lambda=1.5, order=1)
lw2<-WLocpoly(mcycle$accel, mcycle$times, lambda=1.5, order=2)
lw3<-WLocpoly(mcycle$accel, mcycle$times, lambda=1.5, order=3)
span <- c("linear", "quadratic", "cubic")
plot(accel~times, data=mcycle,main="Weighted local linear, quadratic and cubic fits")
lines(fitted(lw1)~mcycle$times, col=1, lty=1)
lines(fitted(lw2)~mcycle$times, col=2, lty=2)
lines(fitted(lw3)~mcycle$times, col=3, lty=3)
legend(1.5,50, legend = span, col = 1:3,
lty = 1:3, cex = .8, y.intersp = 1)
Run the code above in your browser using DataLab