# predictPlot # command to make a prediction interval plot for a simple linear regression # x is the explanatory variable # y is the response variable # interval="prediction" is a confidence interval for individual observations. # interval="confidence" is a confidence interval for the population mean. # -------------- Directions ------------------------------------ # Save this file as a text file on your computer. # From R, use the File menu and select "Import R Source Code..." # Browse for the file predictPlot.R that you saved earlier. # You can then use predictPlot as a function. # # ------------- Example ---------------------------------------- # ex0723 <- read.table(file.choose(),header=T,sep=",") # attach(ex0723) # predictPlot(DURATION,INTERVAL) # predictPlot(DURATION,INTERVAL,interval="prediction") # predictPlot(DURATION,INTERVAL,interval="prediction",level=0.99) predictPlot <- function(x,y,interval=c("confidence","prediction"),level=0.95) { interval <- match.arg(interval) fit <- lm(y ~ x) r <- range(x) new <- data.frame(x=seq(r[1],r[2],length=200)) limits <- predict.lm(fit,new,interval=interval,level=level) ylim <- range(c(y,limits[,2],limits[,3])) matplot(new$x,limits[,-1],xlab=deparse(substitute(x)),ylab=deparse(substitute(y)),lty=2,col=2,type="l",xlim=r,ylim=ylim) points(x,y) abline(fit) invisible() }