#================================================================= # Figure 15.2.R. # R script to calculate least squares estimates for pronghorn data. # Variable for prediction is y, spring fawn count. # Predictor variables are size of adult pronghorn population (u), # annual inches precipitation (v), winter severity index (w; scale # of 1:mild-5:severe. # Script produces a time plot of the data along with overlayed # predictions. #================================================================= #----------------------------------------------------- # Input the data. #----------------------------------------------------- Pronghorn=read.table("pronghorn.txt",header=TRUE) # Change file name # if necessary. attach(Pronghorn) #----------------------------------------------------- # Calculate least squares intercept and slope. #----------------------------------------------------- n=length(y) # Number of observations is n. X=matrix(1,n,4) # Form the X matrix: col 1 has 1’s, X[,2]=u # cols 2-4 have predictor variables. X[,3]=v # --- X[,4]=w # --- b=solve(t(X)%*%X,t(X)%*%y) # Least squares estimates in b; # t( ) is transpose function. # Alternatively can use # b=solve((t(X)%*%X)%*%t(X)%*%y . #----------------------------------------------------- # Draw a time plot of data, with superimposed least # squares predictions. #----------------------------------------------------- plot((1:8),y,type="o",xlab="time (yr)", ylab="spring fawn count") # Time plot of data. ypredict=X%*%b # Calculate predicted y values at values of predictors. points((1:8),ypredict,type="p",pch=2) # Plot predicted values # with points. #----------------------------------------------------- # Print the least squares estimates to the console. #----------------------------------------------------- "least squares intercept and coefficients: " b