0
0
R Programmingprogramming~5 mins

Linear regression (lm) in R Programming

Choose your learning style9 modes available
Introduction

Linear regression helps us find a straight line that best fits data points. It shows how one thing changes when another changes.

To predict house prices based on size.
To understand how study hours affect exam scores.
To see the relationship between temperature and ice cream sales.
To estimate sales based on advertising budget.
To check if weight affects blood pressure.
Syntax
R Programming
lm(formula, data)

formula shows the relationship, like y ~ x means y depends on x.

data is the dataset where variables come from.

Examples
Predict miles per gallon (mpg) using car weight (wt) from the mtcars dataset.
R Programming
lm(mpg ~ wt, data = mtcars)
Predict sepal length using sepal width from the iris dataset.
R Programming
lm(Sepal.Length ~ Sepal.Width, data = iris)
Predict house price using size and number of bedrooms.
R Programming
lm(price ~ size + bedrooms, data = housing_data)
Sample Program

This code fits a linear model to predict miles per gallon (mpg) based on car weight (wt) using the mtcars dataset. Then it shows a summary of the model.

R Programming
data(mtcars)
model <- lm(mpg ~ wt, data = mtcars)
summary(model)
OutputSuccess
Important Notes

The lm() function fits a straight line to data.

Check the summary to see how well the line fits and which variables matter.

Always look at residuals to understand errors in prediction.

Summary

Linear regression finds a line to predict one variable from others.

Use lm() with a formula and data.

Summary shows model details like coefficients and fit quality.