diff options
Diffstat (limited to 'polynomial_regression2.R')
-rw-r--r-- | polynomial_regression2.R | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/polynomial_regression2.R b/polynomial_regression2.R new file mode 100644 index 0000000..321206e --- /dev/null +++ b/polynomial_regression2.R @@ -0,0 +1,39 @@ +# polynomial_regression2.R +# Purpose: to demonstrate polynomial regression using poly() +# +# +# Created by Hui Lan on 26 April 2018 + + +### Functions ### + +f <- function(x) +{ + # the true function + # y <- 0.5 + 1.5*x + 0.5*x^2 # also try quadratic function + y <- 0.5 + 1.5*x # y is implicitly returned. don't need a return statement +} + + + +### main ### +sd.err <- 2 +N <- 12 +x1 <- rnorm(N, mean=5, sd=3) # my data for the the predictor variable X1 +e = rnorm(N, mean=0, sd=sd.err) # error term +y <- f(x1) + e # my data for the response variable Y + + +model <- lm(y~x1) # call linear model fit. use ?lm to get details of this function +model +summary(model) + +D <- data.frame(Y=y, X1=x1) +model.polynomial <- lm(Y ~ poly(X1,11), data=D) +par(mfrow=c(1,1)) +plot(x1, y, pch='+') +abline(model, lwd=1, col='green') +curve(f, from=min(x1), to=max(x1), col='red', add=T) +num.interval <- 100 +new.x <- seq(min(x1),max(x1),length=num.interval) +lines(new.x,predict(model.polynomial, data.frame(X1=new.x)), col="blue") |