Multiple Linear Regression in R [With Graphs & Examples]

As a data scientist, I often find myself engaged in predictive analysis for various projects. Linear regression, encompassing simple and multiple linear regression, serves as a vital statistical tool for establishing relationships between dependent and independent variables. In the field of data science and analytics, R holds immense importance. Specifically, multiple linear regression in R becomes invaluable when dealing with scenarios where a single response variable (Y) exhibits a linear dependence on multiple predictor variables. Mastering this aspect of R enhances my ability to conduct precise predictive modeling in a variety of projects. 

What is a Linear Regression?

Linear regression models are used to show or predict the relationship between a dependent and an independent variable. When there are two or more independent variables used in the regression analysis, the model is not simply linear but a multiple regression model.

Simple linear regression is used for predicting the value of one variable by us

Check out our data science courses to upskill another variable. A straight line represents the relationship between the two variables with linear regression.

No Coding Experience Required. 360° Career support. PG Diploma in Machine Learning & AI from IIIT-B and upGrad.

There is a linear relationship between a dependent variable with two or more independent variables in multiple regression. The relationship can also be non-linear, and the dependent and independent variables will not follow a straight line.

Check out our data science courses to upskill yourself.

Pictorial representation of Multiple linear regression model predictions

Linear and non-linear regression are used to track a response using two or more variables. The non-linear regression is created from assumptions from trial and error and is comparatively difficult to execute.

What is Multiple Linear Regression?

Multiple linear regression is a statistical analysis technique used to predict a variable’s outcome based on two or more variables. It is an extension of linear regression and also known as multiple regression. The variable to be predicted is the dependent variable, and the variables used to predict the value of the dependent variable are known as independent or explanatory variables.

The multiple linear regression enables analysts to determine the variation of the model and each independent variable’s relative contribution. Multiple regression is of two types, linear and non-linear regression.

Multiple linear regression is one of the data mining methods to determine the relations and concealed patterns among the variables in huge. It is a type of regression method and belongs to predictive mining techniques. It helps to determine the relationship and presume the linearity between predictors and targets. But the relationship may not always be linear. So, it is inevitable to discover a statistical technique that fits the data and helps determine unbiased results.

The multiple linear regression in R is an extended version of linear regression that enables you to know the relationship between two or more variables. On the other hand, linear regression determines the relationship between two variables only. Let’s explore more on the multiple linear regression in R.

Multiple Regression Formula

The multiple regression with three predictor variables (x) predicting variable y is expressed as the following equation:

 y = z0 + z1*x1 + z2*x2 + z3*x3

The “z” values represent the regression weights and are the beta coefficients. They are the association between the predictor variable and the outcome.

  • yi is dependent or predicted variable
  • z0 is the y-intercept, i.e., the value of y when x1 and x2 are 0
  • z1 and z2 are the regression coefficients representing the change in y related to a one-unit change in x1 and x2, respectively.

Assumptions of Multiple Linear Regression

We have known the brief about multiple regression and the basic formula. However, there are some assumptions of which the multiple linear regression is based on detailed as below:

i. Relationship Between Dependent And Independent Variables

The dependent variable relates linearly with each independent variable. To check the linear relationships, a scatterplot is created and is observed for the linearity. If the scatterplot relationship is non-linear, then a non-linear regression is performed, or the data is transferred using statistical software.

ii. The Independent Variables Are Not Much Correlated

The data should not display multicollinearity, which happens in case the independent variables are highly correlated to each other. This will create problems in fetching out the specific variable contributing to the variance in the dependent variable.

iii. The Residual Variance is Constant

Multiple linear regression assumes that the remaining variables’ error is similar at each point of the linear model. This is known as homoscedasticity. When the data analysis is done, the standard residuals against the predicted values are plotted to determine if the points are properly distributed across independent variables’ values.

Explore our Popular Data Science Courses

iv. Observation Independence

The observations should be of each other, and the residual values should be independent. The Durbin Watson statistic works best for this.

The method shows values from 0 to 4, where a value between 0 and 2 shows positive autocorrelation, and from 2 to 4 shows negative autocorrelation. The midpoint, a value of 2, shows there is no autocorrelation.

Data Science Advanced Certification, 250+ Hiring Partners, 300+ Hours of Learning, 0% EMI

v. Multivariate Normality

Multivariate normality happens with normally distributed residuals. Moreover, it happens when the independent variables are highly correlated. For this assumption, it is observed how the values of residuals are distributed. It can be tested using two methods,

· A histogram showing a superimposed normal curve and

· The Normal Probability Plot method.

vi. Homoscedasticity

This assumption specifies that the error terms’ variance is identical to the independent variables’ values. It features a plot of standardized residuals vs. predicted values. This plot demonstrates whether points are uniformly distributed over all values of the independent variables.

For this assumption, multiple linear regression needs a minimum of two independent variables. They can be ordinal, nominal, or interval/ratio level variables.  Regarding the sample size, the regression analysis needs a minimum of 20 cases per independent variable for the analysis.

Firstly, the multiple linear regression in R needs that the relationship between the dependent and independent variables is linear.  Scatterplots help to test the linearity assumption.

Secondly, the multiple linear regression analysis states that the errors between predicted and observed values (i.e., the regressions’ residuals) must be normally distributed. You can check this assumption after looking at a Q-Q-Plot or histogram.  Normality can be checked with a goodness of fit test (including the Kolmogorov-Smirnov test). Note that this test should be performed on the residuals themselves.

Read our popular Data Science Articles

Instances Where Multiple Linear Regression is Applied

Multiple linear regression is a very important aspect from an analyst’s point of view. Before looking at the details of how to plot multiple linear regression in R, you must know the instances where multiple linear regression is applied. Here are some of the examples where the concept can be applicable:

i. As the value of the dependent variable is correlated to the independent variables, multiple regression is used to predict the expected yield of a crop at certain rainfall, temperature, and fertilizer level.

ii. Multiple linear regression analysis is also used to predict trends and future values. This is particularly useful to predict the price for gold in the six months from now.

iii. In a particular example where the relationship between the distance covered by an UBER driver and the driver’s age and the number of years of experience of the driver is taken out. In this regression, the dependent variable is the distance covered by the UBER driver. The independent variables are the age of the driver and the number of years of experience in driving.

iv. Another example where multiple regressions analysis is used in finding the relation between the GPA of a class of students and the number of hours they study and the students’ height.  The dependent variable in this regression is the GPA, and the independent variables are the number of study hours and the heights of the students.

v. The relation between the salary of a group of employees in an organization and the number of years of exporganizationthe employees’ age can be determined with a regression analysis. The dependent variable for this regression is the salary, and the independent variables are the experience and age of the employees.

Multiple linear regression in R example can be about the selling price of a house. This price can depend on the location’s desirability, the number of bedrooms and bathrooms, the year when the house was constructed, the square footage area of the lot, and many other factors.

Top Data Science Skills to Learn

Another multiple linear regression in R example can be the height of a child that depends on the height of the mother and the father, nutrition gained, and environmental factors.

Also Read: 6 Types of Regression Models in Machine Learning You Should Know About

How to Build Digital & Data Mindset Done 4-10-2022
How upGrad helps for your Data Science Career? Done 4-10-2022
How to Build Digital & Data Mindset Done 4-10-2022
How upGrad helps for your Data Science Career? Done 4-10-2022
ODE Thought Leadership Presentation Done 4-10-2022
The Future of Consumer Data in an Open Data Economy Done 4-10-2022
Transformation & Opportunities in Analytics & Insights Done 4-10-2022
The Future of Consumer Data in an Open Data Economy Done 4-10-2022
Transformation & Opportunities in Analytics & Insights Done 4-10-2022
ODE Thought Leadership Presentation Done 4-10-2022

Multiple Linear Regression in R

There are many ways multiple linear regression can be executed but is commonly done via statistical software. One of the most used software is R which is free, powerful, and available easily. We will first learn the steps to perform the regression with R, followed by an example of a clear understanding.

Steps to Perform Multiple Regression in R

  1. Data Collection: The data to be used in the prediction is collected.
  2. Data Capturing in R: Capturing the data using the code and importing a CSV file
  3. Checking Data Linearity with R: It is important to make sure that a linear relationship exists between the dependent and the independent variable. It can be done using scatter plots or the code in R
  4. Applying Multiple Linear Regression in R:Using code to apply multiple linear regression in R to obtain a set of coefficients.
  5. Making Prediction with R: A predicted value is determined at the end.

Multiple Regression Implementation in R

We will understand how R is implemented when a survey is conducted at a certain number of places by the public health researchers to gather the data on the population who smoke, who travel to the work, and the people with a heart disease. 

Step-by-Step Guide for Multiple Linear Regression in R:

The following step-by-step guide helps you to know how to plot multiple linear regression in R:

i. Load the dataset and run the following code

lm<-lm(heart.disease ~ biking + smoking, data =

The data set heart. Data calculates the effect of the independent variables biking and smoking on the dependent variable heart disease using ‘lm()’ (the equation for the linear model).

ii. Interpreting Results

use the summary() function to view the results of the model:


This function puts the most important parameters obtained from the linear model into a table that looks as below:

From this table we can infer:

  • The formula of ‘Call’,
  • The residuals of the model (‘Residuals’). If the residuals are roughly centred around zero and with similar spread on either side (median 0.03, and min and max -2 and 2), then the model fits heteroscedasticity assumptions.
  • The regression coefficients of the model (‘Coefficients’).      

Row 1 of the coefficients table (Intercept): This is the y-intercept of the regression equation and used to know the estimated intercept to plug in the regression equation and predict the dependent variable values.

heart disease = 15 + (-0.2*biking) + (0.178*smoking) ± e

Evaluating the Goodness of Fit of the Model:

From the multiple linear regression model output, you can determine the fitted multiple linear regression equation. This equation is useful to make predictions about the mpg value for new observations. You can go through a few metrics as discussed below to evaluate how “good” the multiple regression model in R fits the data:

  • Multiple R-Squared:

This metric of multiple regression in R measures the strength of the linear relationship between the response variable and the predictor variables. A multiple R-squared of 1 shows a perfect linear relationship, whereas a multiple R-squared of 0 shows that no linear relationship exists.

Multiple R alternatively denotes the square root of R-squared.  It is the variance proportion in the response variable which can be explicated by the predictor variables.

  • Residual Standard Error:

This metric of multiple regression in R calculates the average distance that the observed values fall from the particular regression line.

 How to choose a good linear model?

A model that fulfills the application’s conditions is the minimum requirement. However, you may find different models that fulfil this criterion. So, you may get confused about how to select between various valid models of multiple regression plot in R.

The 3 most common tools to choose a good linear model are:

  • The coefficient of determination R2
  • The p-value associated with the model
  •  The Akaike Information Criterion

It is important to note that the first two approaches are suitable for both simple and multiple linear regression; the third one applies to multiple linear regression only.

How to Improve the multiple linear regression model  

Here’s a step-by-step explanation of how to improve a multiple linear regression model 

  1. Thorough Data Exploration and Cleaning:
  • Begin by understanding your dataset thoroughly. 
  • Identify and handle missing values, outliers, and inconsistencies. 
  • Ensure that your data is in a format suitable for analysis. 
  1. Feature Engineering:
  • Create new features that might capture additional information. 
  • Transform existing features to improve their representation. 
  1. Variable Selection:
  • Carefully choose relevant variables that contribute to the prediction. 
  • Use techniques like backward elimination, forward selection, or recursive feature elimination. 
  1. Multicollinearity Check:
  • Assess correlations among predictor variables to avoid multicollinearity. 
  • Remove or combine highly correlated variables to enhance model stability. 
  1. Regularization Techniques:
  • Apply regularization methods like Ridge or Lasso regression to prevent overfitting. 
  • These techniques add a penalty term to the model parameters, discouraging overly complex models. 
  1. Cross-Validation:
  • Use cross-validation techniques to evaluate model performance on different subsets of the data. 
  • Assess how well the model generalizes to unseen data. 
  1. Continuous Refinement:
  • Iteratively refine the model based on insights from the evaluation. 
  • Fine-tune parameters and features to improve predictive accuracy. 
  1. Validation Against Unseen Data:
  • Validate the model against a separate set of data not used during training. 
  • Ensure that the model performs well on new, unseen observations. 
  1. Feedback Loops:
  • Establish feedback loops based on ongoing model performance. 
  • Adjust the model as needed and incorporate new data for continuous improvement. 
  1. Iterative Optimization:
  • Keep optimizing the model based on changing data patterns and business requirements. 
  • Embrace a continuous improvement mindset for sustained model effectiveness. 

Benefits of using Multiple Linear Regression in R:

  • In real-world examples, multiple linear regression is used more often than simple linear regression.  The following points justify its benefits:
  • Multiple linear regression in R help you to assess the relationship between two variables and also controls the effect of other variables.
  • With data collection getting streamlined, more variables can be incorporated when assessing data.
  • The relevant modules help you to understand more about multiple regressions.
  • The multiple linear regression modules present the concept’s outlines of multiple regression analysis and the dissimilarity between the simple and multiple regression analysis methods using relevant examples.

The related module explains the stages involved in the decision process of multiple regression plot in R analysis. Based on the plot, the module calculates the regression using dependent and independent variables.

Some Terms Related To Multiple Regression

i.  Estimate Column: It is the estimated effect and is also called the regression coefficient or r2 value. The estimates tell that for every one percent increase in biking to work there is an associated 0.2 percent decrease in heart disease, and for every percent increase in smoking there is a .17 percent increase in heart disease.

ii.  Std.error: It displays the standard error of the estimate. This is a number that shows variation around the estimates of the regression coefficient.

iii.  t Value: It displays the test statistic. It is a t-value from a two-sided t-test.

iv. Pr( > | t | ): It is the p-value which shows the probability of occurrence of t-value.

Reporting the Results

We should include the estimated effect, the standard estimate error, and the p-value.

In the above example, the significant relationships between the frequency of biking to work and heart disease and the frequency of smoking and heart disease were found to be p < 0.001.

The heart disease frequency is decreased by 0.2% (or ± 0.0014) for every 1% increase in biking. The heart disease frequency is increased by 0.178% (or ± 0.0035) for every 1% increase in smoking.

Graphical Representation of the Findings

The effects of multiple independent variables on the dependent variable can be shown in a graph. In this, only one independent variable can be plotted on the x-axis.

Multiple Linear Regression: Graphical Representation

Here, the predicted values of the dependent variable (heart disease) across the observed values for the percentage of people biking to work are plotted.

For the effect of smoking on the independent variable, the predicted values are calculated, keeping smoking constant at the minimum, mean, and maximum rates of smoking.

Also Read: Linear Regression Vs. Logistic Regression: Difference Between Linear Regression & Logistic Regression

Final Words

In this post, I’ve taken you through the intricate world of multiple linear regression, aiming to simplify its complexities. I’ve focused on how we apply this method in R to enhance our prediction capabilities. My goal was to demystify this advanced statistical technique, making it accessible and understandable. By breaking down the steps and illustrating how it aids in refining predictions, I hope to have provided you with valuable insights. This journey through multiple linear regression in R is designed to arm you with the knowledge to apply these concepts effectively in your projects, leading to more accurate and reliable outcomes.

If you’re enthusiastic about advancing your journey in data science and expanding your proficiency in R and other languages, I invite you to enroll Advanced Certification Program in Data Science is tailor-made for working professionals, offering over 300 hours of immersive learning and ongoing mentorship to enhance your career in the dynamic field of data science. 

What is the use of the R programming language?

Over the last decade, the R programming language has risen to become the most popular tool for computational statistics, perception, and data science, thanks to frequent usage in academia and business. R Programming applications range from hypothetical, computational statistics and the hard sciences like astronomy, chemistry, and genetics to practical applications in business, drug advancement, finance, health care, marketing, medicine, and many other fields. R Programming is the major programming tool used by many quantitative analysts in finance.

What is linear regression used for?

Linear regression analysis predicts the value of one variable depending on the value of another. The variable you wish to forecast is referred to as the dependent variable. The variable you are using to forecast the value of the other variable is known as the independent variable. This type of analysis calculates the coefficients of a linear equation that includes one or more free variables that best foretell the value of the dependent variable. Linear regression is used to match a straight line or surface that minimizes the differences between anticipated and true output values.

Is R programming tough?

No, R programming is easy to learn. R programming is a statistical computing and graphics programming language that users may use to clean, analyze, and graph their data. Researchers from several fields extensively use it to estimate and show results and by statistics and research techniques professors. One of R's most significant features is that it is open-source, which means that anybody may access the underlying code that runs the program and add their own code for free. Anyone can develop their own R code, which implies that anyone can contribute to R's extensive toolset.

Want to share this article?

Prepare for a Career of the Future

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Data Science Course

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks