##### Code for Basic linear Regression in R ### Importing data # Don't call your data 'data' - that word already has a meaning in R help(read.csv) datum=read.csv(file.choose()) ### creates a data frame named datum from imported csv file ### check data was imported properly names(datum) ### column headers of data file head(datum) ### column headers of data file plus first 6 rows of data head(datum,10) ### number of rows of data can be changed summary(datum) ### summary statistics for datum ### Create a scatterplot of data #help(plot) ### help file for plot function #plot(Y~X,data=datum) ### creates a scatter plot between 'Y' and 'X' variables in 'datum' #Replace 'Y' and 'X' with whatever those columns are actually called plot(Biomass~Rainfall,data=datum) ### scatterplot of data used in example ### Run regression using linear model help(lm) ### help file for 'linear model' - most important function in class #results=lm(Y~X,data=datum) ### runs a linear regression between 'Y' and 'X' columns in 'datum', call results 'results' #Replace 'Y' and 'X' with whatever those columns are actually called results=lm(Biomass~Rainfall,data=datum) ### linear regression of data used in example summary(results) ### prints a summary of 'results' # note slope and constant as well of t-tests and p-values of estimates anova(results) ### generate an anova table of regression - not very useful as doesn't give anything other than p # note F-statistic of full model - same as t-test in single variable regression #coef(results) ### shows you the coefficient estimates from 'results' #summary(results)$coef ### another way of extraction coefficients that also includes SE #summary(results)$coef[1,] ### extracts all information for the intercept #summary(results$coef[,2] ### extract standard errors for both variables ### Generate confidence intervals for parameters confint(results) #calculates confidence limits on slope and intercept ### Plot regression line over data #help(abline) ### function for plotting a straight line on plotted data # requires either a lm object or values for a (intercept) and b (slope) abline(results) ### plots results on the already created plot # Note must have run regression first # Note won't do anything if you haven't plotted data.