# R code for Lecture 2 # R code for chapter 1 (part 2) # Example 1 mydata = read.table("data010201.txt") #read the data X = mydata$V1 # select X Y = mydata$V2 # select Y plot(X, Y) # plot the observations (data) myreg = lm(Y~X) # do the linear regression summary(myreg) # output the estimation lines(X, myreg$fitted) # plot the fitted title("Scatter of (X,Y) and fitted linear regression model") newX <- data.frame(X = c(-3, 3, 0.5)) predict(myreg, newX) # Obtain confidence intervals for beta_0 and beta_1. confint(myreg, level=0.95) # R code for chapter 1 (part 3) mydata = read.table("data010301.txt") X = mydata$V1 # define X Y = mydata$V2 # define Y plot(X, Y) # plot the observations (data) myreg = lm(Y~X) # do the linear regression summary(myreg) # output the estimation plot(X, Y) # plot the observations (data) lines(X, myreg$fitted) # plot the fitted #part a newX = data.frame(X = c(4)) predEY = predict(myreg, newX, interval="confidence", level=0.95) predEY #part b newX = data.frame(X = c(4)) predY = predict(myreg, newX, interval="prediction", level=0.95) predY #part c newX = data.frame(X = c(10:10:130)) predEYband = predict(myreg, newX, interval="confidence", level=0.95) lines(data.matrix(newX), data.matrix(predEYband[,2]), col="red", lty=4) # add red and dash lines for the upper band lines(data.matrix(newX), data.matrix(predEYband[,3]), col="red", lty=4) # add red and dash plot for the lower band title('regression analysis for the Toluca Company data')