Learn Before
Code

Example of Linear Regression Using R

Here is an example of using R to do a simple linear regression.

#MASS package is a very large collection of data sets and #functions library(MASS) #ISLR package includes the data sets associated with this #book library(ISLR) lm.fit=lm(medv∼lstat,data=Boston) # medv as a response, lstat as a predictor summary(lm.fit) # gives us pvalues and standard errors for the coefficients, as well as the R2 statistic and F-statistic for the model confint(lm.fit) # obtain a confidence interval predict (lm.fit ,data.frame(lstat=c(5,10,15)), interval="confidence") #prediction in confidence intervals predict (lm.fit ,data.frame(lstat=c(5,10,15)), interval="prediction") #prediction in prediction intervals attach(Boston) # attach data to Boston plot(lstat ,medv) abline(lm.fit ,lwd=3,col="red") # draw out the regression line

Expected output (plot and abline only): The expected output from the plot and abline commands

0

2

Updated 2020-04-05

Tags

Data Science