Fitting a linear regression model with lm
The simplest model in regression is linear regression, which is best used when there is only one predictor variable, and the relationship between the response variable and independent variable is linear. In this recipe, we demonstrate how to fit the model to data using the lm
function.
Getting ready
Download the house rental dataset from https://raw.githubusercontent.com/ywchiu/rcookbook/master/chapter11/house_rental.csv first, and ensure you have installed R on your operating system.
How to do it…
Perform the following steps to fit data into a simple linear regression model:
- Read the house rental data into an R session:
> house <- read.csv('house_rental.csv', header=TRUE)
- Fit the independent variable
Sqft
and dependent variablePrice
toglm
:> lmfit <- lm(Price ~ Sqft, data=house) > lmfit Call: lm(formula = Price ~ Sqft, data = house) Coefficients: (Intercept) Sqft 3425.13 38.33
- Visualize the fitted...