# R Programming Tutorial for Linear Regression

## Fitting of Simple Linear Regression

Load the data into R. The procedure for loading of data files has been shown in previous R tutorials. Here, we use a data set from a pre-installed package “fma”.

## Loading Data set from a Package in R

{` To load data from the package in R, use the commands: >data (package=”fma”) This instantly presents a list of all data sets available within the package. Now, to load the data set “advert”, use the command: >data(advert) Now print the data in R by: >advert`}

## How to Use R software for carrying out Linear Regression Analysis?

To fit the data into a simple linear regression model using R programming we use the following commands:

{` Define a variable name (here, model) and use the command: >model <- lm (sals~advert, data=advert) To view the intercept and slope of regression in R, print > model`}

{`To print the entire summary of the regression using R software, use the command: >summary (model)`}

{`The following command can be used to find the residuals of individual observations: >residuals (model)`}

## How to Draw a Scatter Plot using R?

{`To draw a scatter plot between sales and advert we use the following command: >plot (sales~advert, data= advert, main=” Sales and Advertising expenditure”, xlab=” Advertising expenditure”, ylab=” sales”) `}

main is used to define the title of the scatterplot while xlab and ylab are used to set X-axis and Y-axis labels.

### How to display the Line of best Fit in Linear Regression scatter plot in R?

{`Display line of best fit by using the following the command: >abline(model)`}

### How to use R programming software for Data FORECAST?

{`Forecast data when adverting expenditure is 30. Use the following command: >predict(model, newdata=data.frame(advert=30)) `}