#### Overview of this book

This cookbook offers a range of data analysis samples in simple and straightforward R code, providing step-by-step resources and time-saving methods to help you solve data problems efficiently. The first section deals with how to create R functions to avoid the unnecessary duplication of code. You will learn how to prepare, process, and perform sophisticated ETL for heterogeneous data sources with R packages. An example of data manipulation is provided, illustrating how to use the “dplyr” and “data.table” packages to efficiently process larger data structures. We also focus on “ggplot2” and show you how to create advanced figures for data exploration. In addition, you will learn how to build an interactive report using the “ggvis” package. Later chapters offer insight into time series analysis on financial data, while there is detailed information on the hot topic of machine learning, including data classification, regression, clustering, association rule mining, and dimension reduction. By the end of this book, you will understand how to resolve issues and will be able to comfortably offer solutions to problems encountered while performing data analysis.
R for Data Science Cookbook
Credits
www.PacktPub.com
Preface
Free Chapter
Functions in R
Data Preprocessing and Preparation
Visualizing Data with ggplot2
Making Interactive Reports
Simulation from Probability Distributions
Statistical Inference in R
Time Series Mining with R
Index

## 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.

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:

1. Read the house rental data into an R session:

```> house <- read.csv('house_rental.csv', header=TRUE)
```
2. Fit the independent variable `Sqft` and dependent variable `Price` to `glm`:

```> lmfit <- lm(Price ~ Sqft, data=house)
> lmfit

Call:
lm(formula = Price ~ Sqft, data = house)

Coefficients:
(Intercept)         Sqft
3425.13        38.33
```
3. Visualize the fitted line with the `plot...`