# R script for lecture 3 in STK4900/9900

# Slide 3-4: Linear regression -------------------------------------------------

trees <- read.table("http://www.uio.no/studier/emner/matnat/math/STK4900/data/trees.txt",header=T) 
plot(trees)

fit.height <- lm(volume~height, data=trees) 
summary(fit.height)

fit.height <- lm(volume~diameter, data=trees) 
summary(fit.height)



# Slide 7-9: Linear regression (cont) ------------------------------------------

fit.both <- lm(volume~diameter+height, data=trees) 
summary(fit.both)

fit.both <- lm(volume~diameter+I(diameter^2)+height, data=trees)
summary(fit.both)

fit.log <- lm(log(volume)~log(height)+log(diameter), data=trees) 
summary(fit.log)



# Slide 18: Binary predictor - t-test ------------------------------------------

cont <- c(0.228, 0.207, 0.234, 0.220, 0.217, 0.228, 0.209, 0.221, 0.204, 0.220, 0.203, 0.219, 0.218, 0.245, 0.210)
treat <- c(0.250, 0.237, 0.217, 0.206, 0.247, 0.228, 0.245, 0.232, 0.267, 0.261, 0.221, 0.219, 0.232, 0.209, 0.255)

t.test(x=treat, y=cont , var.equal=TRUE)



# Slide 20/23: Binary predictor - linear regression ----------------------------

bonedensity <- data.frame(density=c(cont,treat), group=c(rep("cont",length(cont)),rep("treat",length(treat))))

lm.density <- lm(density~group, data=bonedensity)
summary(lm.density)

lm.density.sum <- lm(density~group, data=bonedensity, contrasts=list(group="contr.sum"))
summary(lm.density.sum)



# Slide 28: Categorical predictor ---------------------------------------------

rats <- read.table("http://www.uio.no/studier/emner/matnat/math/STK4900/data/rats.txt",header=T) 
rats$diet <- factor(rats$diet)
boxplot(time~diet, data=rats)

fit.rats <- lm(time~diet, data=rats)
summary(fit.rats)
anova(fit.rats)
