set.seed(2) ## set.seed(1) ## Questions 1-7 gen_weights <- function(x) -0.0004*x^3 + 0.025*x^2 + 2*x + 50 age <- sample(40:80,1000,replace=TRUE) trueFx <- gen_weights(age) noise <- rnorm(n=length(age),mean=0,sd=10) weight <- trueFx + noise dat <- data.frame(age,weight,trueFx,noise) plot(age,weight,pch=19,cex=0.4) ## Question 8-15 ksmooth1 <- ksmooth(age,weight,kernel="box",bandwidth=10) ksmooth1 names(ksmooth1) lines(ksmooth1$x,ksmooth1$y,col="red",lwd=3) ksmooth2 <- ksmooth(age,weight,kernel="normal",bandwidth=10) ksmooth2 names(ksmooth2) lines(ksmooth2$x,ksmooth2$y,col="blue",lwd=3) ksmooth3 <- ksmooth(age,weight,kernel="normal",bandwidth=5) names(ksmooth3) lines(ksmooth3$x,ksmooth3$y,col="green",lwd=3,lty=2) ksmooth4 <- ksmooth(age,weight,kernel="normal",bandwidth=20) names(ksmooth4) lines(ksmooth4$x,ksmooth4$y,col="purple",lwd=3,lty=3) legend("bottomright",cex=0.8,lwd=3,lty=c(1,1,2,3),c("box bw=10","normal bw=10","normal bw=5","normal bw=20"),col=c("red","blue","green","purple")) ## Questions 16-22 plot(age,weight,pch=19,cex=0.4) lm1 <- lm(weight ~ age) summary(lm1) abline(a=lm1$coefficients[1],b=lm1$coefficients[2],col="red",lwd=3) ## Alternatively to the previous line you can use the short-cut abline(lm1,col="red",lwd=3) lm2 <- lm(weight ~ age + I(age^2)) lm3 <- lm(weight ~ age + I(age^2) + I(age^3)) summary(lm2) summary(lm3) quad <- function(x) lm2$coefficients[1] + lm2$coefficients[2]*x + lm2$coefficients[3]*x^2 cube <- function(x) lm3$coefficients[1] + lm3$coefficients[2]*x + lm3$coefficients[3]*x^2 + lm3$coefficients[4]*x^3 curve(quad, add=TRUE, col="blue", lwd=3) curve(cube, add=TRUE, col="green", lwd=3, lty=2) legend("bottomright",cex=0.8,lwd=3,lty=c(1,1,2),c("linear","quadratic","cubic"),col=c("red","blue","green")) anova(lm2,lm3)