# Ricker_polynomial.R
# Polynomial regression for Ricker data

# Load necessary libraries
library(ggplot2)
library(car)
library(QuantPsyc)

# Read in data set
rickerdata <- read.table(header=T,colClasses=rep("numeric",2),text="
n logR
5  0.42
10  0.33
20  0.48
30  0.03
40 -0.18
50 -0.16
60  0.08
70 -1.20
80 -1.45
90 -1.72
100 -2.67
")

# Apply transformations here
rickerdata <- transform(rickerdata,x=n-mean(n))
rickerdata <- transform(rickerdata,x2=x^2)
rickerdata <- transform(rickerdata,x3=x^3)

# Print data
rickerdata

# Plot data and fit smooth line
ggplot(rickerdata,aes(n,logR))+
geom_point()+geom_smooth()

# Polynomial regression analysis
regout <- lm(logR~x+x2+x3,data=rickerdata)
summary(regout)

# Look at Type I tests to determine order of polynomial
anova(regout)

# Preceding analysis suggests second-order polynomial adequate
# Plot the data and second-order polynomial
ggplot(rickerdata,aes(n,logR))+
geom_point()+
stat_smooth(method="lm",formula=y~poly(x,2))

# Polynomial regression with second-order polynomial
regout2 <- lm(logR~x+x2,data=rickerdata)
summary(regout2)

# 95% confidence intervals for regression coefficients
confint(regout2)

# Standardized regression coefficients
lm.beta(regout2)

# Tolerance values (1/vif)
tol <- 1/vif(regout2)
tol

# Variance inflation factors
vif(regout2)

# Residual-residual plots
avPlots(regout2)

# Diagnostic plots to check regression assumptions
p <- predict(regout2)
r <- resid(regout2)
plot(p,r)
qqnorm(r)
