# Explain with a case study of implementing simple linear regression using R.

413    Asked by Nabhashahin in Data Science , Asked on Nov 21, 2019

# Simple Linear Regression

First we will import the dataset

Now we split the dataset into the Training set and Test set

# install.packages('caTools')

library(caTools)

set.seed(123)

split = sample.split(dataset\$Salary, SplitRatio = 2/3)

training_set = subset(dataset, split == TRUE)

test_set = subset(dataset, split == FALSE)

Now we will perform Feature Scaling

# training_set = scale(training_set)

# test_set = scale(test_set)

Finally we fit the Simple Linear Regression to the Training set

regressor = lm(formula = Salary ~ YearsExperience,

data = training_set)

Now we predict the Test set results

y_pred = predict(regressor, newdata = test_set)

Now we will Visualise the Training set results

library(ggplot2)

ggplot() +

geom_point(aes(x = training_set\$YearsExperience, y = training_set\$Salary),

colour = 'red') +

geom_line(aes(x = training_set\$YearsExperience, y = predict(regressor, newdata = training_set)),

colour = 'blue') +

ggtitle('Salary vs Experience (Training set)') +

xlab('Years of experience') +

ylab('Salary')

Now we Visualise the Test set results

library(ggplot2)

ggplot() +geom_point(aes(x = test_set\$YearsExperience, y = test_set\$Salary),colour='red')+geom_line(aes(xtraining_set\$YearsExperience, y =predict(regressor, newdata = training_set)), colour = 'blue') + ggtitle('Salary vs Experience (Test set)') +xlab('Years of experience') + ylab('Salary')