Group Members
Matric_Number Name
22052749 Darvhind Magayndran
22056384 Aloysius Pallis Gerad
22064355 Tiun Wai Ren
22098083 Zhang Leping
22093085 Han Xiang

1 Introduction

The dataset analyzes a flight booking dataset obtained from “Ease My Trip” website containing 300,261 data points and 11 features. The goal is to uncover valuable insights from the data that will aid passengers in making booking decisions.

2 Objectives

  1. Regression Problem: Predicting airline ticket prices using the linear regression algorithm. This aids in understanding the impact of various features on ticket prices and allows for estimating future prices.

  2. Classification Problem: Determining whether the airline company affects ticket prices. This can be achieved through a classification algorithm (e.g., logistic regression) to ascertain if there are significant differences in prices among different airlines.

By addressing these two questions, we aim to provide information to travelers about price fluctuations and offer recommendations to airlines for optimizing pricing strategies. Simultaneously, this analysis contributes to understanding the impact of different factors on airfare, providing valuable insights to the entire aviation industry.

3 Data Collection & Data Understanding

# import relevant packages
library(dplyr)
library(lubridate)
library(ggplot2)
library(tidyr)
library(caret)
library(plotly)
library(readr)
library(rpart)
library(rpart.plot)
library(corrplot)
library(fastDummies)
library(randomForest)
library(Metrics)

# importing the datasets
businessData <- read.csv("business.csv")
economyData <- read.csv("economy.csv")

3.1 Tittle: business.csv

This dataset comprises comprehensive details on business class flights, featuring 11 columns and 93,488 rows of data. The following is an explanation of the fields:

  1. date: Date of Travel (Column type: character)
  2. airline: Categorical variable with 2 airlines, these two variables are Air India and Vistara (Column type: character)
  3. ch_code: Flight Character Code, divided into UK and AI (Column type: character)
  4. num_code: Flight Numerical Code (Column type: integer)
  5. dep_time: Departure Time (Column type: character)
  6. from: Source city (Column type: character)
  7. time_taken: Duration of flight (Column type: character)
  8. stop: There are one-stop, non-stop, and others (Column type: character)
  9. arr_time: Arrival time (Column type: character)
  10. to: Destination city (Column type: character)
  11. price: The air ticket price (Column type: character)
business_column_types <- sapply(businessData, typeof)

# Output the type of each column
print(business_column_types)
##        date     airline     ch_code    num_code    dep_time        from 
## "character" "character" "character"   "integer" "character" "character" 
##  time_taken        stop    arr_time          to       price 
## "character" "character" "character" "character" "character"
str(businessData)
## 'data.frame':    93487 obs. of  11 variables:
##  $ date      : chr  "11-02-2022" "11-02-2022" "11-02-2022" "11-02-2022" ...
##  $ airline   : chr  "Air India" "Air India" "Air India" "Air India" ...
##  $ ch_code   : chr  "AI" "AI" "AI" "AI" ...
##  $ num_code  : int  868 624 531 839 544 985 479 473 871 977 ...
##  $ dep_time  : chr  "18:00" "19:00" "20:00" "21:25" ...
##  $ from      : chr  "Delhi" "Delhi" "Delhi" "Delhi" ...
##  $ time_taken: chr  "02h 00m" "02h 15m" "24h 45m" "26h 30m" ...
##  $ stop      : chr  "non-stop " "non-stop " "1-stop\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t" "1-stop\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t" ...
##  $ arr_time  : chr  "20:00" "21:15" "20:45" "23:55" ...
##  $ to        : chr  "Mumbai" "Mumbai" "Mumbai" "Mumbai" ...
##  $ price     : chr  "25,612" "25,612" "42,220" "44,450" ...

3.2 Tittle:economy.csv

This dataset provides information on economy class flights, encompassing 206,774 observations across 11 variables. The types of each column and some sample data are as follows:

  1. date: Date of Travel (Column type: character)
  2. airline: Categorical variable with Vistara (33%), Air India (23%), and Other (44%).(Column type: character)
  3. ch_code: Flight Character Code (Column type: character)
  4. num_code: Flight Numerical Code (Column type: integer)
  5. dep_time: Departure Time (Column type: character)
  6. from: Source city (Column type: character)
  7. time_taken: Duration of flight (Column type: character)
  8. stop: There are one-stop,non-stop, and others (Column type: character)
  9. arr_time: Arrival time (Column type: character)
  10. to: Destination city (Column type: character)
  11. price: The air ticket price (Column type: character)
economy_column_types <- sapply(economyData, typeof)

# Output the type of each column
print(economy_column_types)
##        date     airline     ch_code    num_code    dep_time        from 
## "character" "character" "character"   "integer" "character" "character" 
##  time_taken        stop    arr_time          to       price 
## "character" "character" "character" "character" "character"
str(economyData)
## 'data.frame':    206774 obs. of  11 variables:
##  $ date      : chr  "11-02-2022" "11-02-2022" "11-02-2022" "11-02-2022" ...
##  $ airline   : chr  "SpiceJet" "SpiceJet" "AirAsia" "Vistara" ...
##  $ ch_code   : chr  "SG" "SG" "I5" "UK" ...
##  $ num_code  : int  8709 8157 764 995 963 945 927 951 334 336 ...
##  $ dep_time  : chr  "18:55" "06:20" "04:25" "10:20" ...
##  $ from      : chr  "Delhi" "Delhi" "Delhi" "Delhi" ...
##  $ time_taken: chr  "02h 10m" "02h 20m" "02h 10m" "02h 15m" ...
##  $ stop      : chr  "non-stop " "non-stop " "non-stop " "non-stop " ...
##  $ arr_time  : chr  "21:05" "08:40" "06:35" "12:35" ...
##  $ to        : chr  "Mumbai" "Mumbai" "Mumbai" "Mumbai" ...
##  $ price     : chr  "5,953" "5,953" "5,956" "5,955" ...

4 Data Preparation

Data preparation is a critical phase in any data science project, laying the groundwork for meaningful analysis and model development. This process involves cleaning, transforming, and organizing raw data into a structured format that is suitable for analysis. Feature selection and engineering are also integral components, allowing for the identification and creation of relevant variables that contribute to the predictive power of models. Additionally, normalization and scaling techniques are applied to bring diverse data into a standardized range.

4.1 Data Cleaning

Data cleaning is a phase in the data preprocessing pipeline that involves identifying and rectifying errors, inconsistencies, and inaccuracies within datasets. This process is essential for ensuring the quality and reliability of the data before analysis or modeling. Data cleaning encompasses various tasks such as handling missing values, detecting and removing outliers, standardizing formats, and resolving inconsistencies in data entries. Through techniques like imputation, interpolation, and outlier detection, data cleaning aims to enhance the overall quality of information, facilitating more accurate and reliable insights for decision-making.

4.1.1 Merging Data

Data merging helps to enrich the dataset by incorporating complementary information, providing a more in depth view of the data. In this case, merging the dataset allows us to further investigate the features of both the economy and business classes.

# adding a new "class" feature to indicate that the data belongs to the economy dataset
economyData["class"] <- "Economy"
head(economyData)
##         date  airline ch_code num_code dep_time  from time_taken      stop
## 1 11-02-2022 SpiceJet      SG     8709    18:55 Delhi    02h 10m non-stop 
## 2 11-02-2022 SpiceJet      SG     8157    06:20 Delhi    02h 20m non-stop 
## 3 11-02-2022  AirAsia      I5      764    04:25 Delhi    02h 10m non-stop 
## 4 11-02-2022  Vistara      UK      995    10:20 Delhi    02h 15m non-stop 
## 5 11-02-2022  Vistara      UK      963    08:50 Delhi    02h 20m non-stop 
## 6 11-02-2022  Vistara      UK      945    11:40 Delhi    02h 20m non-stop 
##   arr_time     to price   class
## 1    21:05 Mumbai 5,953 Economy
## 2    08:40 Mumbai 5,953 Economy
## 3    06:35 Mumbai 5,956 Economy
## 4    12:35 Mumbai 5,955 Economy
## 5    11:10 Mumbai 5,955 Economy
## 6    14:00 Mumbai 5,955 Economy
# adding a new "class" feature to indicate that the data belongs to the business dataset
businessData["class"] <- "Business"
head(businessData)
##         date   airline ch_code num_code dep_time  from time_taken
## 1 11-02-2022 Air India      AI      868    18:00 Delhi    02h 00m
## 2 11-02-2022 Air India      AI      624    19:00 Delhi    02h 15m
## 3 11-02-2022 Air India      AI      531    20:00 Delhi    24h 45m
## 4 11-02-2022 Air India      AI      839    21:25 Delhi    26h 30m
## 5 11-02-2022 Air India      AI      544    17:15 Delhi    06h 40m
## 6 11-02-2022   Vistara      UK      985    19:50 Delhi    02h 10m
##                                                         stop arr_time     to
## 1                                                  non-stop     20:00 Mumbai
## 2                                                  non-stop     21:15 Mumbai
## 3 1-stop\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t    20:45 Mumbai
## 4 1-stop\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t    23:55 Mumbai
## 5 1-stop\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t    23:55 Mumbai
## 6                                                  non-stop     22:00 Mumbai
##    price    class
## 1 25,612 Business
## 2 25,612 Business
## 3 42,220 Business
## 4 44,450 Business
## 5 46,690 Business
## 6 50,264 Business
# merging the economy and business datasets
economyBusinessData <- rbind(economyData, businessData)

# merging the "ch_code" and "num_code" features to create a new "flight" feature that displays the flight code
economyBusinessData <- transform(economyBusinessData, num_code = as.character(num_code))
economyBusinessData["flight"] <- paste(economyBusinessData$ch_code, economyBusinessData$num_code, sep = "-")
economyBusinessData <- subset(economyBusinessData, select = -c(ch_code, num_code))

head(economyBusinessData)
##         date  airline dep_time  from time_taken      stop arr_time     to price
## 1 11-02-2022 SpiceJet    18:55 Delhi    02h 10m non-stop     21:05 Mumbai 5,953
## 2 11-02-2022 SpiceJet    06:20 Delhi    02h 20m non-stop     08:40 Mumbai 5,953
## 3 11-02-2022  AirAsia    04:25 Delhi    02h 10m non-stop     06:35 Mumbai 5,956
## 4 11-02-2022  Vistara    10:20 Delhi    02h 15m non-stop     12:35 Mumbai 5,955
## 5 11-02-2022  Vistara    08:50 Delhi    02h 20m non-stop     11:10 Mumbai 5,955
## 6 11-02-2022  Vistara    11:40 Delhi    02h 20m non-stop     14:00 Mumbai 5,955
##     class  flight
## 1 Economy SG-8709
## 2 Economy SG-8157
## 3 Economy  I5-764
## 4 Economy  UK-995
## 5 Economy  UK-963
## 6 Economy  UK-945

4.2 Renaming Columns

In cleaning the dataset, the column names can be renamed with more intuitive/descriptive names so that the analysis can be done with greater ease

# renaming the features
names(economyBusinessData)[names(economyBusinessData) == "dep_time"] <- "departure_time"
names(economyBusinessData)[names(economyBusinessData) == "from"] <- "source_city"
names(economyBusinessData)[names(economyBusinessData) == "time_taken"] <- "duration"
names(economyBusinessData)[names(economyBusinessData) == "stop"] <- "stops"
names(economyBusinessData)[names(economyBusinessData) == "arr_time"] <- "arrival_time"
names(economyBusinessData)[names(economyBusinessData) == "to"] <- "destination_city"

head(economyBusinessData)
##         date  airline departure_time source_city duration     stops
## 1 11-02-2022 SpiceJet          18:55       Delhi  02h 10m non-stop 
## 2 11-02-2022 SpiceJet          06:20       Delhi  02h 20m non-stop 
## 3 11-02-2022  AirAsia          04:25       Delhi  02h 10m non-stop 
## 4 11-02-2022  Vistara          10:20       Delhi  02h 15m non-stop 
## 5 11-02-2022  Vistara          08:50       Delhi  02h 20m non-stop 
## 6 11-02-2022  Vistara          11:40       Delhi  02h 20m non-stop 
##   arrival_time destination_city price   class  flight
## 1        21:05           Mumbai 5,953 Economy SG-8709
## 2        08:40           Mumbai 5,953 Economy SG-8157
## 3        06:35           Mumbai 5,956 Economy  I5-764
## 4        12:35           Mumbai 5,955 Economy  UK-995
## 5        11:10           Mumbai 5,955 Economy  UK-963
## 6        14:00           Mumbai 5,955 Economy  UK-945

4.3 Standardizing Data

# converting "departure time" feature into parts of the day for ease of analysis
economyBusinessData$departure_time <- strptime(economyBusinessData$departure_time, "%H:%M")

economyBusinessData$departure_time <-
  ifelse(economyBusinessData$departure_time >= strptime("00:01", "%H:%M") & economyBusinessData$departure_time <= strptime("04:00", "%H:%M"), "Late_Night",
  ifelse(economyBusinessData$departure_time >= strptime("04:01", "%H:%M") & economyBusinessData$departure_time <= strptime("08:00", "%H:%M"), "Early_Morning",
  ifelse(economyBusinessData$departure_time >= strptime("08:01", "%H:%M") & economyBusinessData$departure_time <= strptime("12:00", "%H:%M"), "Morning",
  ifelse(economyBusinessData$departure_time >= strptime("12:01", "%H:%M") & economyBusinessData$departure_time <= strptime("16:00", "%H:%M"), "Afternoon",
  ifelse(economyBusinessData$departure_time >= strptime("16:01", "%H:%M") & economyBusinessData$departure_time <= strptime("20:00", "%H:%M"), "Evening",
  ifelse(economyBusinessData$departure_time >= strptime("20:01", "%H:%M") & economyBusinessData$departure_time <= strptime("23:59", "%H:%M"), "Night", "Night"))))))
  
# converting "arrival time" feature into parts of the day for ease of analysis
economyBusinessData$arrival_time <- strptime(economyBusinessData$arrival_time, "%H:%M")

economyBusinessData$arrival_time <-
  ifelse(economyBusinessData$arrival_time >= strptime("00:01", "%H:%M") & economyBusinessData$arrival_time <= strptime("04:00", "%H:%M"), "Late_Night",
  ifelse(economyBusinessData$arrival_time >= strptime("04:01", "%H:%M") & economyBusinessData$arrival_time <= strptime("08:00", "%H:%M"), "Early_Morning",
  ifelse(economyBusinessData$arrival_time >= strptime("08:01", "%H:%M") & economyBusinessData$arrival_time <= strptime("12:00", "%H:%M"), "Morning",
  ifelse(economyBusinessData$arrival_time >= strptime("12:01", "%H:%M") & economyBusinessData$arrival_time <= strptime("16:00", "%H:%M"), "Afternoon",
  ifelse(economyBusinessData$arrival_time >= strptime("16:01", "%H:%M") & economyBusinessData$arrival_time <= strptime("20:00", "%H:%M"), "Evening",
  ifelse(economyBusinessData$arrival_time >= strptime("20:01", "%H:%M") & economyBusinessData$arrival_time <= strptime("23:59", "%H:%M"), "Night", "Night"))))))

head(economyBusinessData)
##         date  airline departure_time source_city duration     stops
## 1 11-02-2022 SpiceJet        Evening       Delhi  02h 10m non-stop 
## 2 11-02-2022 SpiceJet  Early_Morning       Delhi  02h 20m non-stop 
## 3 11-02-2022  AirAsia  Early_Morning       Delhi  02h 10m non-stop 
## 4 11-02-2022  Vistara        Morning       Delhi  02h 15m non-stop 
## 5 11-02-2022  Vistara        Morning       Delhi  02h 20m non-stop 
## 6 11-02-2022  Vistara        Morning       Delhi  02h 20m non-stop 
##    arrival_time destination_city price   class  flight
## 1         Night           Mumbai 5,953 Economy SG-8709
## 2       Morning           Mumbai 5,953 Economy SG-8157
## 3 Early_Morning           Mumbai 5,956 Economy  I5-764
## 4     Afternoon           Mumbai 5,955 Economy  UK-995
## 5       Morning           Mumbai 5,955 Economy  UK-963
## 6     Afternoon           Mumbai 5,955 Economy  UK-945
# converting duration to float values
# e.g. duration is stored as "02h 10m"
economyBusinessData$duration <- as.numeric(substr(economyBusinessData$duration, 1, 2)) + as.numeric(substr(economyBusinessData$duration, 5, 6))/60

# round the float value to 2 decimal places
economyBusinessData$duration <- round(economyBusinessData$duration, 2)

head(economyBusinessData)
##         date  airline departure_time source_city duration     stops
## 1 11-02-2022 SpiceJet        Evening       Delhi     2.17 non-stop 
## 2 11-02-2022 SpiceJet  Early_Morning       Delhi     2.33 non-stop 
## 3 11-02-2022  AirAsia  Early_Morning       Delhi     2.17 non-stop 
## 4 11-02-2022  Vistara        Morning       Delhi     2.25 non-stop 
## 5 11-02-2022  Vistara        Morning       Delhi     2.33 non-stop 
## 6 11-02-2022  Vistara        Morning       Delhi     2.33 non-stop 
##    arrival_time destination_city price   class  flight
## 1         Night           Mumbai 5,953 Economy SG-8709
## 2       Morning           Mumbai 5,953 Economy SG-8157
## 3 Early_Morning           Mumbai 5,956 Economy  I5-764
## 4     Afternoon           Mumbai 5,955 Economy  UK-995
## 5       Morning           Mumbai 5,955 Economy  UK-963
## 6     Afternoon           Mumbai 5,955 Economy  UK-945
# converting the string in the "date" feature to date data type
# there are inconsistencies in the way the dates are recorded like in dd/mm/yyyy and mm-dd-yyyy formats
#economyBusinessData$date <- dmy(economyBusinessData$date)
# converting the "price" feature to numeric data type
economyBusinessData$price <- as.numeric(gsub(",", "", economyBusinessData$price))

head(economyBusinessData)
##         date  airline departure_time source_city duration     stops
## 1 11-02-2022 SpiceJet        Evening       Delhi     2.17 non-stop 
## 2 11-02-2022 SpiceJet  Early_Morning       Delhi     2.33 non-stop 
## 3 11-02-2022  AirAsia  Early_Morning       Delhi     2.17 non-stop 
## 4 11-02-2022  Vistara        Morning       Delhi     2.25 non-stop 
## 5 11-02-2022  Vistara        Morning       Delhi     2.33 non-stop 
## 6 11-02-2022  Vistara        Morning       Delhi     2.33 non-stop 
##    arrival_time destination_city price   class  flight
## 1         Night           Mumbai  5953 Economy SG-8709
## 2       Morning           Mumbai  5953 Economy SG-8157
## 3 Early_Morning           Mumbai  5956 Economy  I5-764
## 4     Afternoon           Mumbai  5955 Economy  UK-995
## 5       Morning           Mumbai  5955 Economy  UK-963
## 6     Afternoon           Mumbai  5955 Economy  UK-945

4.4 Handling Data Inconsistencies

# by running the code below, we can see that the "stops" feature contains lots of data inconsistencies
head(economyBusinessData$stops, 30)
##  [1] "non-stop "                                                        
##  [2] "non-stop "                                                        
##  [3] "non-stop "                                                        
##  [4] "non-stop "                                                        
##  [5] "non-stop "                                                        
##  [6] "non-stop "                                                        
##  [7] "non-stop "                                                        
##  [8] "non-stop "                                                        
##  [9] "non-stop "                                                        
## [10] "non-stop "                                                        
## [11] "non-stop "                                                        
## [12] "non-stop "                                                        
## [13] "non-stop "                                                        
## [14] "non-stop "                                                        
## [15] "non-stop "                                                        
## [16] "non-stop "                                                        
## [17] "non-stop "                                                        
## [18] "non-stop "                                                        
## [19] "1-stop\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t"       
## [20] "1-stop\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t"       
## [21] "1-stop\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t"       
## [22] "1-stop\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t"       
## [23] "1-stop\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t"       
## [24] "1-stop\n\t\t\t\t\t\t\t\t\t\t\t\tVia IXU\n\t\t\t\t\t\t\t\t\t\t\t\t"
## [25] "non-stop "                                                        
## [26] "non-stop "                                                        
## [27] "non-stop "                                                        
## [28] "1-stop\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t"       
## [29] "non-stop "                                                        
## [30] "non-stop "
# replacing the strings in the "stops" feature to the number of stops in numeric data type
economyBusinessData["stops"] <- as.numeric(gsub("[^0-9]", "", economyBusinessData$stops))

# replacing the NA values in the "stop" feature with 0 to indicate no stops
economyBusinessData[is.na(economyBusinessData)] <- 0

head(economyBusinessData)
##         date  airline departure_time source_city duration stops  arrival_time
## 1 11-02-2022 SpiceJet        Evening       Delhi     2.17     0         Night
## 2 11-02-2022 SpiceJet  Early_Morning       Delhi     2.33     0       Morning
## 3 11-02-2022  AirAsia  Early_Morning       Delhi     2.17     0 Early_Morning
## 4 11-02-2022  Vistara        Morning       Delhi     2.25     0     Afternoon
## 5 11-02-2022  Vistara        Morning       Delhi     2.33     0       Morning
## 6 11-02-2022  Vistara        Morning       Delhi     2.33     0     Afternoon
##   destination_city price   class  flight
## 1           Mumbai  5953 Economy SG-8709
## 2           Mumbai  5953 Economy SG-8157
## 3           Mumbai  5956 Economy  I5-764
## 4           Mumbai  5955 Economy  UK-995
## 5           Mumbai  5955 Economy  UK-963
## 6           Mumbai  5955 Economy  UK-945

4.5 Reordering Data

# reordering the columns
economyBusinessData <- economyBusinessData[, c(1, 2, 11, 10, 4, 8, 3, 7, 5, 6, 9)]

head(economyBusinessData)
##         date  airline  flight   class source_city destination_city
## 1 11-02-2022 SpiceJet SG-8709 Economy       Delhi           Mumbai
## 2 11-02-2022 SpiceJet SG-8157 Economy       Delhi           Mumbai
## 3 11-02-2022  AirAsia  I5-764 Economy       Delhi           Mumbai
## 4 11-02-2022  Vistara  UK-995 Economy       Delhi           Mumbai
## 5 11-02-2022  Vistara  UK-963 Economy       Delhi           Mumbai
## 6 11-02-2022  Vistara  UK-945 Economy       Delhi           Mumbai
##   departure_time  arrival_time duration stops price
## 1        Evening         Night     2.17     0  5953
## 2  Early_Morning       Morning     2.33     0  5953
## 3  Early_Morning Early_Morning     2.17     0  5956
## 4        Morning     Afternoon     2.25     0  5955
## 5        Morning       Morning     2.33     0  5955
## 6        Morning     Afternoon     2.33     0  5955
# exporting the cleaned dataframe to a csv file
write.csv(economyBusinessData, file="cleaned_df.csv")

# clean dataset to use
cleanData <- economyBusinessData
#cleanData

5 Exploratory Data Analysis

Exploratory Data Analysis (EDA) is a data analysis approach that focuses on finding patterns, anomalies, testing hypotheses, and checking assumptions. It can be done in a visual and quantitative method, and is a critical step before formal modeling, offering initial insights to guide the next process.

5.1 Data Exploration

In our analysis, when passengers plan to buy flight tickets, they consider factors such as Airline, Class, Departure/Arrival Time, and the Number of Stops. It is obvious that, for instance, business class tickets are typically more expensive than economy class tickets.

Firstly, we aim to find which airline is the most popular.

# df <- cleanData
# customer count by Airline
df <- cleanData
options(scipen = 999)
df %>% 
  group_by(airline) %>%
  summarise(count = n()) %>%
  ggplot(aes(x=airline, y=count)) +
   geom_text(aes(label = round(count, 2)), vjust = -0.5) +
  geom_col()

From the code above, most popular airline is Vistara, followed by Air India.

Then, we display the average price by airline.

# Average ticket price for each airline
ggplot(df, aes(x = airline, y = price, fill = airline)) +
  geom_bar(stat = "summary", fun = "mean", position = "dodge") +
  stat_summary(geom = "text", fun = function(x) round(mean(x), 2),
               aes(label = sprintf("%.2f", after_stat(y))), position = position_dodge(width = 0.9), vjust = -0.5) +
  labs(title = "Average Ticket Price by Airline",
       x = "Airline",
       y = "Average Price") +
  theme_minimal()

The chart indicates that the most expensive airline is Vistara, with Air India being the second most expensive.

Secondly, we explore the class distribution in terms of price and passenger numbers.

# Average price by Business & Economy Class
Budget=df %>%
   group_by(class)
Bd = Budget %>%
   summarise(Cost=mean(price),Flights=n())
 
adist=plot_ly(Bd, labels = ~class, values = ~Cost, type = "pie")

adist%>%
   layout(title = 'Price distribution by class',
                     xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
                     yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
# The mean price of Business class outweighs Economy by more than 8 times

The chart shows that the mean price of Business Class outweighs Economy by more than 8 times,

# passengers number distribution by class 
adist=plot_ly(Bd, labels = ~class, values = ~Flights, type = "pie")

adist%>%
   layout(title = 'Class distribution',
                     xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
                     yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
# The demand for Economy class outweighs the Business class by 2 times.

and the demand for Economy Class is twice that of Business Class.

Thirdly, we examine the difference in average price between departure and arrival times by airline.

# Average ticket price for departure time
ggplot(df, aes(x = departure_time, y = price, fill = airline)) +
  geom_bar(stat = "summary", fun = "mean", position = "dodge") +
  labs(title = "Average Ticket Price by Departure Time and Airline",
       x = "Departure Time",
       y = "Average Price") +
  theme_minimal()

# the most expensive airline is Vistara, but departure in afternoon will be cheaper
# the cheapest airline is Airasia, but it will be little higher in early-morning

For departure time, the analysis finds that the most expensive airline is Vistara, but tickets are cheaper when departing in the afternoon. The cheapest airline is Airasia, with prices slightly higher in the early morning.

# Average ticket price for arrival time
ggplot(df, aes(x = arrival_time, y = price, fill = airline)) +
  geom_bar(stat = "summary", fun = "mean", position = "dodge") +
  labs(title = "Average Ticket Price by Arrival Time and Airline",
       x = "Arrival Time",
       y = "Average Price") +
  theme_minimal()

# the most expensive airline is Vistara, but departure in afternoon will be cheaper
# the cheapest airline is Airasia, but it will be little higher in evening

For arrival time, similar trends are observed, but Airasia price is higher in the evening.

Finally, to know the price variation by the number of stops

df$stops_cat <-
  ifelse(df$stops==0, "no_stop",
  ifelse(df$stops==1, "1_stop",
  ifelse(df$stops==2,"2_stops","2+_stops")))
# grouped by stops
ggplot(df, aes(x = stops_cat, y = price)) +
  geom_boxplot()

# the price of no stops will be cheapest
# and the most price fluctuation is one stop
# for outliers, there are most in two-or-more stops
df$stops_cat <- NULL

The findings indicate that non-stop flights are usually the cheapest, and the most price fluctuation occurs with one-stop flights. For outliers, the most occur in flights with two or more stops.

5.2 correlation analysis

# the flight and date are not necessary in the analysis
df$flight <- NULL
df$date <- NULL
df <- df %>%
  mutate_if(is.character, as.factor)%>%
  mutate_if(is.factor, as.numeric)%>%mutate_if(is.integer,as.numeric)
head(df)
##   airline class source_city destination_city departure_time arrival_time
## 1       5     2           3                6              3            6
## 2       5     2           3                6              2            5
## 3       2     2           3                6              2            2
## 4       8     2           3                6              5            1
## 5       8     2           3                6              5            5
## 6       8     2           3                6              5            1
##   duration stops price
## 1     2.17     0  5953
## 2     2.33     0  5953
## 3     2.17     0  5956
## 4     2.25     0  5955
## 5     2.33     0  5955
## 6     2.33     0  5955
df_numeric <- df %>% 
  select_if(~is.numeric(.))

cor_matrix <- cor(df_numeric)
corrplot(cor_matrix, method="color")

# the most relevant with price is class 

correlation analysis reveals that the most correlation with price is associated with class.

6 Modelling & Results

6.1 Classification Modelling

6.1.1 Classification of Pricing Category

As classification model does not works well with continuous dependent variable, we will need to categorize the price first. In this code block, three price levels (Low, Medium, and High) is created based on class.

  • High: when price is higher than 1.2(Median Price) for that class
  • Low: when it is lower than 0.8(Median Price)
  • Medium: in between High and Low
# Calculate Median Price Grouped by Source & Destination City
data_num <- df_numeric
median_prices <- data_num %>%
  group_by(class) %>%
  summarize(MedianPrice = median(price, na.rm = TRUE), .groups = 'drop')

# Create New Dataframe by combining median prices with numerical dataframe
new_data_num <- data_num %>%
  left_join(median_prices, by = c("class"))

# Categorize prices relative to the median price for that route
new_data_num <- new_data_num %>%
  mutate(Price_Category = case_when(
    price < 0.8 * MedianPrice ~ "Low",    
    # Prices less than 80% of the median price are considered 'Low'
    price > 1.2 * MedianPrice ~ "High",   
    # Prices more than 120% of the median price are considered 'High'
    TRUE ~ "Medium"                       
    # Prices within +/- 20% of the median are considered 'Medium'
  ))

# Remove the intermediate MedianPrice column
new_data_num <- new_data_num %>% select(-MedianPrice)
head(new_data_num)
##   airline class source_city destination_city departure_time arrival_time
## 1       5     2           3                6              3            6
## 2       5     2           3                6              2            5
## 3       2     2           3                6              2            2
## 4       8     2           3                6              5            1
## 5       8     2           3                6              5            5
## 6       8     2           3                6              5            1
##   duration stops price Price_Category
## 1     2.17     0  5953         Medium
## 2     2.33     0  5953         Medium
## 3     2.17     0  5956         Medium
## 4     2.25     0  5955         Medium
## 5     2.33     0  5955         Medium
## 6     2.33     0  5955         Medium

6.1.2 Incorporate Fullname (Airline, Source City, Destination City)

Rpart are able to handle multi-level categorical variables, therefore we can include the full categorical name back into the dataframe. In this code block, we included the categorical strings from the original dataset for ticket class, airline name, source city, and destination city, which will allow for clearer tree model diagram.

#Append Actual Names of Airline, Source City & Destination City into Dataframe
new_data_num$className<-cleanData$class
new_data_num$airlineName<-cleanData$airline
new_data_num$s_cityName<-cleanData$source_city
new_data_num$d_cityName<-cleanData$destination_city
write.csv(new_data_num, file="new_data_num.csv")

classificationDF <- new_data_num %>% select(-airline, -source_city, -destination_city, -class, -price)
head(classificationDF)
##   departure_time arrival_time duration stops Price_Category className
## 1              3            6     2.17     0         Medium   Economy
## 2              2            5     2.33     0         Medium   Economy
## 3              2            2     2.17     0         Medium   Economy
## 4              5            1     2.25     0         Medium   Economy
## 5              5            5     2.33     0         Medium   Economy
## 6              5            1     2.33     0         Medium   Economy
##   airlineName s_cityName d_cityName
## 1    SpiceJet      Delhi     Mumbai
## 2    SpiceJet      Delhi     Mumbai
## 3     AirAsia      Delhi     Mumbai
## 4     Vistara      Delhi     Mumbai
## 5     Vistara      Delhi     Mumbai
## 6     Vistara      Delhi     Mumbai

6.1.3 Classification Prediction

# Set seed for reproducibility
set.seed(1515)

# Split data to train (80%) and test (20%)
split_classificationDF <- createDataPartition(classificationDF$Price_Category, p = 0.8, list = FALSE)
train_classificationDF <- classificationDF[split_classificationDF, ]
test_classificationDF <- classificationDF[-split_classificationDF, ]

# Train a Decision Tree model using train data set
tree_model <- rpart(Price_Category ~ ., data = train_classificationDF, method = "class")

# Visualize the Decision Tree
rpart.plot(tree_model)

#print(tree_model)

Decision Tree evaluates all possible features and splitting points to find the one that best separates the data into different classes. The splitting point is chosen to maximize the homogeneity of the classes in each resulting subset.

Once a feature and splitting point are chosen, the algorithm creates two child nodes (left and right) representing the subsets of data resulting from the split.

# Make predictions using test data set
predictions <- predict(tree_model, newdata = test_classificationDF, type = "class")
test_classificationDF$Price_Category <- factor(test_classificationDF$Price_Category, levels = levels(predictions))

# Calculate confusion matrix
conf_matrix_classification <- confusionMatrix(predictions, test_classificationDF$Price_Category)

# Print confusion matrix
print(conf_matrix_classification)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction  High   Low Medium
##     High    1443     8    370
##     Low     2486 11035   3175
##     Medium 11908  6734  22892
## 
## Overall Statistics
##                                                
##                Accuracy : 0.589                
##                  95% CI : (0.5851, 0.5929)     
##     No Information Rate : 0.4402               
##     P-Value [Acc > NIR] : < 0.00000000000000022
##                                                
##                   Kappa : 0.3209               
##                                                
##  Mcnemar's Test P-Value : < 0.00000000000000022
## 
## Statistics by Class:
## 
##                      Class: High Class: Low Class: Medium
## Sensitivity              0.09112     0.6207        0.8659
## Specificity              0.99145     0.8661        0.4454
## Pos Pred Value           0.79242     0.6609        0.5512
## Neg Pred Value           0.75281     0.8445        0.8086
## Prevalence               0.26373     0.2960        0.4402
## Detection Rate           0.02403     0.1838        0.3812
## Detection Prevalence     0.03032     0.2780        0.6916
## Balanced Accuracy        0.54128     0.7434        0.6557

6.2 Linear Regression Modelling

6.2.1 Split Train & Test Data

We split the dataset into training and test sets in this code block. Splitting dataset is important for developing, evaluating, and fine-tuning models that are are both accurate and robust against unseen data.

set.seed(1515) 
head(data_num)
##   airline class source_city destination_city departure_time arrival_time
## 1       5     2           3                6              3            6
## 2       5     2           3                6              2            5
## 3       2     2           3                6              2            2
## 4       8     2           3                6              5            1
## 5       8     2           3                6              5            5
## 6       8     2           3                6              5            1
##   duration stops price
## 1     2.17     0  5953
## 2     2.33     0  5953
## 3     2.17     0  5956
## 4     2.25     0  5955
## 5     2.33     0  5955
## 6     2.33     0  5955
indices <- sample(1:nrow(data_num), size = 0.8 * nrow(data_num))
train_dataPrediction <- data_num[indices, ]
test_dataPrediction <- data_num[-indices, ] 

6.2.2 Linear Regression Prediction

# No include flight to let the model generalize better
model <- lm(price ~ ., data = train_dataPrediction)
plot(model, which=1)

We observe a distinct cluster of data in the chart, suggesting that further improvements could be made to this model. One potential approach is to create separate models to predict prices for Business and Economy classes. These models could then be combined in an ensemble to provide a more accurate final prediction.

lm_prediction <- predict(model, newdata = test_dataPrediction)
print(paste("Linear Regression MSE:", mse(test_dataPrediction$price, lm_prediction)))
## [1] "Linear Regression MSE: 51707217.8179875"
print(paste("Linear Regression RMSE:", sqrt(mse(test_dataPrediction$price, lm_prediction))))
## [1] "Linear Regression RMSE: 7190.77310294154"
print(paste("Linear Regression MAE:", mae(test_dataPrediction$price, lm_prediction)))
## [1] "Linear Regression MAE: 4847.58410328193"

6.2.3 Cross Validation

In this code block, we employ cross validation method to ensure the model is reliable by evaluating its performance across multiple subsets of the data. Another reason to use Cross validation is to reduce the risk of over-fitting and providing a more accurate assessment of its predictive capabilities.

# Set up cross-validation for linear regression
train_control <- trainControl(method = "cv", number = 10) # 10-fold cross-validation

# Train cv model
model_cv <- train(price ~ ., 
                     data = train_dataPrediction, 
                     method = "lm", 
                     trControl = train_control)

# Summarize the cv model result
print(model_cv)
## Linear Regression 
## 
## 240208 samples
##      8 predictor
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 216187, 216188, 216186, 216187, 216187, 216188, ... 
## Resampling results:
## 
##   RMSE      Rsquared   MAE     
##   7161.773  0.9003153  4833.123
## 
## Tuning parameter 'intercept' was held constant at a value of TRUE
  • The high R-squared value indicates a good fit of the model to the data, as it captures most of the variability in the response variable. But since the RMSE and MAE values are relatively high, this suggest that on average, the model’s predictions are quite off from the actual value.
  • The result from cross-validation and the initial model evaluation are close (similar RMSE, MAE, and R-squared values), which suggests that the model is stable and generalizes well to unseen data.

7 Conclusion

In this comprehensive analysis of flight booking data from the “Ease My Trip” website, we aimed to extract valuable insights to assist passengers in making informed booking decisions and to enable airlines to optimize their pricing strategies. The data preparation phase was crucial, involving cleaning, merging, and standardizing data. We also transformed certain features like the departure and arrival times into more useful categorical data.

In the EDA, we discovered interesting patterns. For example, Vistara is the most popular and expensive airline, and that the price of business class tickets was, on average, eight times higher than economy class. Based on the metrics statistics, the accuracy of the model is 58.9%. The model is not very accurate. To improve accuracy, few factors can be taken into consideration such as Feature Engineering (Days Left To Book Flights) & Temporal Factors (Seasonal Variations). The linear regression model, while providing a decent R-squared value, had high RMSE and MAE values, suggesting room for improvement in prediction accuracy. The model could potentially be enhanced by treating business and economy class data separately.

This study serves as a beneficial tool for both consumers in planning their travel and airlines in optimizing their pricing strategies.