Logistic Regression in R Programming

Logistic Regression is a classification supervised machine learning algorithm in R programming. Logistic Regression can also be termed Binomial Logistic Regression, Binary Logistic Regression, or Logit Model. Logistic Regression is a Generalized Linear Model. Logistic Regression classifies binary or multi-class data values. So, with the help of logistic Regression, we can build a model which segregates and classify binary data values.

Logistic Regression is mostly used when we have to find the probability of the event’s success and failure. Logistic Regression is another type of regression model where the dependent variable (response variable) has categorical values, namely 0/1, True/False, or Yes/No.

Logistic Regression measures the probability of binary response as the value of the dependent or response variable is based on the mathematical equation relating to it with the predictor variables.

Logistic Regression works on the logit function; this function segregates the binary labeled values in our dataset. In a binomial distribution, the logit function is used as a link function.

Logistic Regression is based on the sigmoid function. The reason is that the input can be anything from -infinity to + infinity, but the output is probability. So it has to be between 0 to 1.

Now, let’s have a look at the simplest Logistic Regression equation:

y = 1/(1+e^-(a+b1x1+b2x2+b3x3+………+bnxn))


Description of the above parameters:


y = response variable (dependent variable)
a = coefficients (constant)
b = coefficients (constant)
x = predictor variable

As we know, the Regression model is created using the glm() function. So the basic syntax of the glm() function is as follows:

SYNTAX:

glm(formula, data, family)


Description of the above parameters:


glm - generalized linear model
formula – formula represents the relationship between the variables
data - data is the dataset that gives the values of these variables
family – It is an R object specifying the details of our model. The value of the R object is binomial for logistic regression. 

Let’s have a look at one example to have a better understanding of the topic:

CODE:

# LOGISTIC REGRESSION
# First step is to select some columns from the mtcars dataset.
input <- mtcars[,c("am","cyl","hp","wt")]


# head is used to print the first part of any vector, dataframe, or matrix.
print(head(input))

By executing the above code in RStudio, the following result is produced:

OUTPUT:

LOGISTIC REGRESSION IN R PROGRAMMING

CREATING REGRESSION MODEL:

Using the glm() function, we will create a Regression model and get the summary of our model for analysis.

CODE:

# LOGISTIC REGRESSION
# First step is to select some columns from the mtcars dataset.
input <- mtcars[,c("am","cyl","hp","wt")]


# head is used to print the first part of any vector, dataframe, or matrix.
print(head(input))


input <- mtcars[,c("am","cyl","hp","wt")]


am.data = glm(formula = am ~ cyl + hp + wt, data = input, family = binomial)


# summary function will quickly summarize our dataframe, vector or matrix. 
print(summary(am.data))

By executing the above code in RStudio, the following result is produced:

OUTPUT:

LOGISTIC REGRESSION IN R PROGRAMMING
LOGISTIC REGRESSION IN R PROGRAMMING

HOW TO PLOT A LOGISTIC REGRESSION CURVE IN R PROGRAMMING?

There are 2 methods of creating a Logistic Regression curve in R programming. They are as follows:

  1. Base R Methods
  2. ggplot2 Package

a) Base R Methods:

  • The first step is to fit the variables in the Logistic Regression model using the glm() function.
  • Then, we will create a dataframe where the variables of the y-axis are changed to their predicted variable by using predict() function.
  • After that, we will create a scatter plot using the plot() function and predicted values using the lines() function.

SYNTAX:

# Logistic Model
glm(formula, family, dataframe)


# Plotting original dataframe
plot(o_dataframe)


# Plotting predicted dataframe
lines(p_dataframe)

EXAMPLE 1:

CODE:

# Fitting Logistic Regression Model
model <- glm(vs ~ wt, data=mtcars, family=binomial)


# Defining new data frame which contains predictor variable
newdata <- data.frame(wt=seq(min(mtcars$wt), max(mtcars$wt),len=500))


# Using fitted model to predict the values of vs
newdata$vs = predict(model, newdata, type="response")


# Plotting logistic regression curve
plot(vs ~ wt, data=mtcars, col="steelblue")
lines(vs ~ wt, newdata, lwd=2)

By executing the above code in RStudio, the following result is produced:

OUTPUT:

LOGISTIC REGRESSION IN R PROGRAMMING

EXAMPLE 2:

CODE:

# Fitting Logistic Regression Model
model <- glm(vs ~ hp, data=mtcars, family=binomial)


# Defining new data frame which contains predictor variable
newdata <- data.frame(hp=seq(min(mtcars$hp), max(mtcars$hp),len=500))


# Using fitted model to predict the values of vs
newdata$vs = predict(model, newdata, type="response")


# Plotting logistic regression curve
plot(vs ~ hp, data=mtcars, col="steelblue")
lines(vs ~ hp, newdata, lwd=2)

By executing the above code in RStudio, the following result is produced:

OUTPUT:

LOGISTIC REGRESSION IN R PROGRAMMING

b) ggplot2 Package:

EXAMPLE 1:

CODE:

# Installing ggplot2 library.
library(ggplot2)


# Plotting logistic regression curve.
ggplot(mtcars, aes(x=wt, y=vs)) + 
  geom_point(alpha=.5) +
  stat_smooth(method="glm", se=FALSE, method.args = list(family=binomial))

By executing the above code in RStudio, the following result is produced:

OUTPUT:

LOGISTIC REGRESSION IN R PROGRAMMING

EXAMPLE 2:

CODE:

# Installing ggplot2 library.
library(ggplot2)


# Plotting logistic regression curve.
ggplot(mtcars, aes(x=hp, y=vs)) + 
  geom_point(alpha=.5) +
  stat_smooth(method="glm", se=FALSE, method.args = list(family=binomial))

By executing the above code in RStudio, the following result is produced:

OUTPUT:

LOGISTIC REGRESSION IN R PROGRAMMING

CONCLUSION:

So, this was all about Logistic Regression in R Programming. And how to plot the curve of Logistic Regression in RStudio.


Related Topics

R Date and Time

R provides very large range of capabilities to deal with times and dates. Generally, dates are internally stored as integers, and depending on the operations we will need, we could...

3 minutes read.

Logistic Regression in R Programming

Logistic Regression is a classification supervised machine learning algorithm in R programming. Logistic Regression can also be termed Binomial Logistic Regression, Binary Logistic Regression, or Logit Model. Logistic Regression is...

4 minutes read.

R JSON File

JSON stands for JavaScript Object Notation. It is a lightweight format for storing and transporting data. JSON file is often used when data is sent from a server to a...

2 minutes read.

R Excel Files

Microsoft Excel is the spreadsheet program which stores data in the .xls and .xlsx format. R has the facility to read directly from these files using some excel specific packages....

2 minutes read.

How to create Histograms in R

R Histograms A Histogram is the graphical representation of the distribution of numeric data. It takes only one numeric variable as input. The variable is cut into several bars (also called...

2 minutes read.

R Variables, Constants and Reserved Words

R Variables Variables are very similar to an open box, where you can put any value of your wish. We can change the values as well. Variables are used to store...

4 minutes read.

R Tutorial

Introduction to R Programming R is nothing but a programming language, also a free software environment. This software used for predictive analysis, statistical analysis, graphical representation, data modeling, and reporting. R...

9 minutes read.

R Switch Statement

It is an alternate way to a nested if…else statement. A switch statement permits an expression to be tested against a list of case values. In short, we can say...

1 minute read.

Analysis of Covariance in R Programming

Analysis of Covariance can also be named ANCOVA. We know that we use the concept of regression analysis for creating models which can explain the effect of the variation in...

2 minutes read.

R Inheritance

One the main concept of object oriented programming is inheritance which allows us to define a new class of existing classes. This means that we can derive new classes from...

5 minutes read.

Scatter Plot in R Programming

A Scatter plot is a type of dispersion graph built to represent the various data points of variables. A Scatter plot is also known as a scatter graph or scattergram.  A scatter plot is used...

4 minutes read.

How to make Boxplots in R

R Boxplots Boxplot is a measure of how well the data is distributed in a data set. It is used to give a summary of one or several numeric variables. The...

3 minutes read.

Binomial Distribution in R Programming

In this article, we will talk about the Binomial distribution in R programming. The binomial distribution is a type of probability distribution. As it is a discrete distribution, it will...

3 minutes read.

R Operators

A symbol that tells the compiler to perform specific mathematical or logical operations is called operator. R language supports mainly 5 different types of operators, which are listed below: Arithmetic...

3 minutes read.

R If Else Statement

If statement It is the most simple decision-making statement. It checks the condition if the condition is true then only it will execute the block of statements written in the ‘if...

2 minutes read.

R Data Types

Data types are used to define the size and type of the variable. In R, there is no need to declare a variable as some data types. The variables are...

4 minutes read.

R Pie Charts

R programming language provides many numbers of libraries to create charts and graphs. A pie-chart is a representation of data as slices of a circle with different colors representing counts...

2 minutes read.

Pie Charts in R Programming

R programming has various libraries to plot various types of charts and graphs. A pie chart is a circular statistical chart or graph, which is divided into slices to represent the numerical...

4 minutes read.

Poisson Distribution in R Programming

Poisson distribution is a type of distribution that deals with the probability distribution of the data values by taking the mean into consideration. Poisson distribution will estimate the probability value for...

3 minutes read.

R Functions

In programming, a function is a group of instructions that you want to use repeatedly, because of their complexity, are better self-contained in sub-program and called when needed. Hence, we can...

4 minutes read.