######
Submitted by : Manoj Pawar

Programming Tutorials: R Programming

Posted on : 2019-09-10

Regression is used to find relation between two variable.One variable is the predictor and other variable is response variable. Linear regression is the term which can used to find response variable whose value is calculated from predictor variable.

Formula for linear regression is :

` Z=ax+b`

Where,

Z: is the response variable.

X : is the predictor variable.

A and b : are the coefficient.

We are using dataset avilable in R environment (i.e:mtcars).Eigher we can pass .csv file as an input or we can create two vector also.if you want to add dataset then it can access by given command:

```
> data("mtcars")
> print.data.frame(mtcars)
Output:
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
```

We are create two vector X and Y. we put some values i.e 'x' vector contain mpg:Miles/(US) gallon and 'y' vector contain cyl :Number of cylinders.After creating vector we are finding relation among them using lm() function.Formula for lm() function is:

```
lm(formula,data)
Where,
Formula: represent relation between A and B (i.e A~B).
Data: it is vector on which formula wil applied.
```

Then, we are predict the result using predict() function:

```
Predict(object,data)
Where,
Object: is variable that stores the relation created by lm() function.
Data: containing new values for predictor variable.
```

we are implementing one example on linear regression shown below: we are calculate number of cylinder required for cars according to miles/gallon.

```
> x<-c(21.0,21.0,22.8,21.4,18.7) // x vector contain mpg:Miles/ gallon.
> y<-c(6,6,4,6,8) // y vector contain cyl :Number of cylinders.
> rel<-lm(y~x)
> print(rel)
Call:
lm(formula = y ~ x)
Coefficients:
(Intercept) x
25.8016 -0.9438
> a<-data.frame(x=18.7)
> result<-predict(rel,a)
> print(result)
1
8.151934
```