# Filename: LSR.R # R script to # - compute equation for least squares regression line # - plot least squares regression line on a graph with the data # - compute the correlation coefficient # - compute the coefficient of determination # LSR = least square regression # Enter the data x = c(2, 5, 2, 4, 6) y = c(4, 7, 5, 8, 11) # Find the equation for the LSR line C = lm(y~x) # Display the equation cat(sprintf("Eqn for LSR: yhat = %f x + %f",coef(C)[2], coef(C)[1]), "\n") # Find the yhat value for each x value yhat = predict(C, data.frame(x)) # Plot the data and the LSR line plot(x,y, pch = 20, xlab = "x", ylab = "y", xlim = c(min(x)-1, max(x)+1), ylim = c(min(y)-1, max(y)+1)) par(new = TRUE) plot(x, yhat, type = "l", xlab = "", ylab = "", xlim = c(min(x)-1, max(x)+1), ylim = c(min(y)-1, max(y)+1), xaxt = "n", yaxt = "n") # Find the correlation coefficient rho = cor(x,y) # Display the correlation coefficient cat(sprintf("rho = %f", rho), "\n") # Display the coefficient of determination cat(sprintf("The regression line accounts for %2.2f%% of the variance in the data", 100*rho^2), "\n")