#-*- S -*-

# Chapter 1    Introduction


# 1.4  An introductory session

library(MASS)
#trellis.device()
if(interactive()) par(ask=T)

x <- rnorm(50)
y <- rnorm(50)

h <- chull(x, y)
plot(x, y)
#polygon(x[h], y[h], dens=15, angle=30) # will not fill
polygon(x[h], y[h], col="cornsilk")

objects()
rm(x,y,h)

x <- rnorm(10000)
y <- rnorm(10000)
truehist(c(x,y+2), nbins=25)
#dd <- con2tr(hist2d(x,y,,,15,15))
#contourplot(z ~ x + y, data=dd, aspect=1)
#wireframe(z ~ x + y, data=dd, drape=T)
#levelplot(z ~ x + y, data=dd, aspect=1)

library(modreg)
x <- seq(1, 20, 0.5)
x
w <- 1 + x/2
y <- x + w*rnorm(x)
dum <-  data.frame(x, y, w)
dum
rm(x, y, w)
fm <- lm(y ~ x,  data=dum)
summary(fm)
fm1 <- lm(y ~ x,  data=dum, weight=1/w^2)
summary(fm1)
lrf <-  loess(y ~ x, dum)
attach(dum)
plot(x, y)
lines(spline(x, fitted(lrf)))
abline(0, 1, lty=3)
abline(fm)
abline(fm1, lty=4)
plot(fitted(fm), resid(fm), xlab="Fitted Values",
   ylab="Residuals")
qqnorm(resid(fm))
qqline(resid(fm))
detach()
rm(fm,fm1,lrf,dum)

library(lqs)
data(hills)
hills
#splom(~ hills) # replace by next line
pairs(hills)
attach(hills)
plot(dist, time)
identify(dist, time, row.names(hills))
abline(lm(time ~ dist))
abline(ltsreg(dist, time), lty=3)
detach()

if(interactive()) {
plot(c(0,1), c(0,1), type="n")
# xy <- locator(type="p") # from 0.65.0
# Prior to 0.65 type="p" is not implemented, so click away
xy <- locator()
points(xy)
abline(lm(y ~ x, xy), col=4)
#abline(rreg(xy$x, xy$y), lty=3, col=3)
abline(ltsreg(xy$x, xy$y), lty=2, col=2)
rm(xy)
}

data(michelson)
attach(michelson)
search()
plot(Expt, Speed,  main="Speed of Light Data", xlab="Experiment No.")
fm <-  aov(Speed ~ Run + Expt)
summary(fm)
fm0 <- update(fm, . ~ .-Run)
anova(fm0, fm)
detach()
rm(fm, fm0)

butterfly <- function()
{
    theta <- seq(0, 24 * pi, len = 2000)
    radius <- exp(cos(theta)) - 2 * cos(4 * theta) +
                              sin(theta/12)^5
    plot(radius * sin(theta), - radius * cos(theta),
        type = "l", axes = F, xlab = "", ylab = "")
}
butterfly()
#usa()

# End of ch01
