#####Chapter 8: Nonlinear Transformations and Nonparametric Smoothers

###Section 8.1:  Differentiation
#Linear Function
funct = expression(a+b*x, 'a,b')
deriva1 <-D(funct,'a')
deriva1
derivb1 <-D(funct,'b')
derivb1

#Nonlinear Function
funct = expression(a*b*x, 'a,b')
summary(deriva1 <-D(funct,'a'))
deriva1
derivb1 <-D(funct,'b')
derivb1

####Section 8.2:  Linearizing Transformations
#Log Transformation
x=c(2,2,2,3,4,6,7,8,9,10,10,12)
y=c(2.99,2.70,3.00,4.02,4.71,5.83,6.28,6.27,6.76,7.04,7.05,7.66)
log.mod <-lm(y~log(x))
summary(log.mod)

#Exponential Transformation
x=c(2,2,2,3,4,6,7,8,9,10,10,12)
y=c(5.92,4.44,6.00,6.94,8.07,13.46,17.62,15.49,23.59,30.08,30.44,55.81)
exp.mod <-lm(log(y)~ x)
summary(exp.mod)
 
#Percentile Changes with Unit changes
change <-seq(1,10,1)
percent <-100*((exp(change*exp.mod$coef[2]))-1)
percha <-rbind(paste(round(percent, 2), "%"));percha

#Power Function
x=c(2,2,2,3,4,6,7,8,9,10,10,12)
y=c(3.02,2.26,3.06,5.61,8.39,17.27,23.05,19.94,29.06,34.71,35.13,53.75)
pow.mod <-lm(log(y)~log(x))
summary(pow.mod) 

#Box-Tidwell Transformation
x=c(2,2,2,3,4,6,7,8,9,10,10,12)
y=c(11.61,11.58,12.18,7.35,5.32,4.26,3.91,2.89,1.63,1.59,1.48,1.71)

#Check Linearity Before Box-Tidwell Transformation
pre.reduced <- lm(y ~ x) 
pre.full <- lm(y ~ factor(x)) 
anova(pre.reduced, pre.full) 

#Box-Tidwell
library(car)                              #attach car package
boxTidwell(y~x)
  
#Reciprocal Transformation 
recip.mod <-lm(y~I(x^-1))
summary(recip.mod)

#Check Linearity After Box-Tidwell Transformation
x.recip=x^-1
post.reduced <- lm(y ~ x.recip) 
post.full <- lm(y ~ factor(x.recip)) 
anova(post.reduced, post.full)  

###Section 8.3: Nonparameteric Smoothers
#Sine Function
x=c(.0931,.1821,.3598,.3982,.5012,.6481,.7361,.7914,.7938,.8259,.8912,.9053)
y=c(.1177,1.3814,-1.2141,-.5542,-3.4717,.7468,1.4446,-.4127,.2300,.9096,1.6794,-.6743)

pure=c(0.802217374,0.968862012,-0.440726043,-0.744914947,-0.955451368,0.196527112,0.880925705,0.998199438,0.996472533,0.91909516,0.49059981,0.363272501)

#Running Average (h=.33)
library(caTools)                               #(attach caTools package)
run.aver <-runmean(y,3)
run.aver

#Running Line (s = 1/3)
run.line33 <-supsmu(x,y,span=.33)
run.line33

#Kernel Regression (h=.17044) 
library(np)                                    #(attach np package)
kernel.reg <-npreg(y~x,bws=.17044,ckertype="gaussian")
fitted(kernel.reg)

#LOESS  (f=.5)
reg.lo <- lowess(y ~ x,f=.5,iter=0)
reg.lo
