# David Kauchak # 11/20/2011 # # Linear regression example # start with some data age = 18:29 height = c(76.1,77,78.1,78.2,78.8,79.7,79.9,81.1,81.2,81.8,82.8,83.5) # we can plot the data using plot plot(age, height) do_built_in = TRUE if( do_built_in ){ # learn a linear model of height to age # tilde is just used to separate the left and right # hand sides of a model formula model = lm(height~age) # we can look at the model print(model) # we can plot the resulting line abline(model) }else{ # do it ourselves! # see http://people.hofstra.edu/Stefan_Waner/RealWorld/calctopic1/regression.html # for the basic equations for a single variable # --------------------------------------------- # some functions slope <- function(x,y){ # Calculate the slope of the best fit line for the data x, y numerator <- length(x) * sum(x*y) - sum(x)*sum(y) denominator <- length(x) * sum(x^2) - sum(x)^2 return(numerator/denominator) } intercept <- function(x,y){ # Calculate the intercept of the best fit line for the data x, y return((sum(y) - slope(x,y) * sum(x))/length(x)) } # --------------------------------------------- # using the functions: get the slope and intercept m = slope(age, height) b = intercept(age, height) # print out the model parameters print(m) print(b) # draw the best fit line abline(b, m) }