## Known weights example
statin <- read.delim("../../data/statin.txt")
summary(lm(LDL~Statin,statin))
summary(lm(LDL~Statin,statin,weights=n))

## Hand speed
handspeed <- read.delim("../../data/handspeed.txt")
attach(handspeed)
plot(Age,Time,col="slateblue",pch=19)
ind <- order(Age)

## Linear fit
fit.w <- lm(Time~Age,handspeed)
for (i in 1:20)
  {
    w <- 1/fit.w$fitted.values^2
    fit.w <- lm(Time~Age,handspeed,weights=w)
  }
fit <- lm(Time~Age,handspeed)
with(handspeed,plot(Time~Age,handspeed,pch=19,col="gray"))
lines(handspeed$Age[ind],fit$fitted.values[ind],lwd=3,col="black")
lines(handspeed$Age[ind],fit.w$fitted.values[ind],lwd=3,col="slateblue")

## Bad idea
fit.w <- lm(Time~Age,handspeed)
for (i in 1:20)
  {
    w <- fit.w$fitted.values^2
    fit.w <- lm(Time~Age,handspeed,weights=w)
  }
fit <- lm(Time~Age,handspeed)

## Quadratic fit
fit.w <- lm(Time~Age+I(Age^2),handspeed)
for (i in 1:20)
  {
    w <- 1/fit.w$fitted.values^2
    fit.w <- lm(Time~Age+I(Age^2),handspeed,weights=w)
  }
fit <- lm(Time~Age+I(Age^2),handspeed)
with(handspeed,plot(Time~Age,handspeed,pch=19,col="gray"))
lines(handspeed$Age[ind],fit$fitted.values[ind],lwd=3,col="black")
lines(handspeed$Age[ind],fit.w$fitted.values[ind],lwd=3,col="slateblue")

