Introduction

The telecom industry is highly competitive and customer retention is crucial for sustainable business growth. This analysis aims to explore the correlation between a customer’s total charges and their churn status.

Data Collection

library(DBI)
library(RMySQL)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.0     ✔ readr     2.1.4
## ✔ ggplot2   3.4.4     ✔ stringr   1.5.1
## ✔ lubridate 1.9.3     ✔ tibble    3.2.1
## ✔ purrr     1.0.2     ✔ tidyr     1.3.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggplot2)
library(nnet)
library(caret)
## Loading required package: lattice
## 
## Attaching package: 'caret'
## 
## The following object is masked from 'package:purrr':
## 
##     lift
## [1] TRUE

Data Exploration

head(telecom_data) # View the first few rows summary(telecom_data) # Summary statistics str(telecom_data) # Structure of the dataset

Checking for missing values

missing_values <- colSums(is.na(telecom_data))

Display missing values

print(missing_values)

Example of ANOVA for total charges across different churn statuses

ANOVA is the Analysis of Variance using a categorical independent variable and a continuous dependent variable; Customer Status - Categorical Total Charges - Continuous

anova_result <- aov(`Total Charges` ~ `Customer Status`, data = telecom_data)

Display the ANOVA result

print(anova_result)
## Call:
##    aov(formula = `Total Charges` ~ `Customer Status`, data = telecom_data)
## 
## Terms:
##                 `Customer Status`   Residuals
## Sum of Squares         6142449370 22060488887
## Deg. of Freedom                 2        4832
## 
## Residual standard error: 2136.703
## Estimated effects may be unbalanced

Example of Kruskal-Wallis test for total charges across churn status

Kruskal-Wallis test is a non-parametric statistical test

kruskal_result <- kruskal.test(`Total Charges` ~ `Customer Status`, data = telecom_data)

Display the Kruskal-Wallis test result

print(kruskal_result)
## 
##  Kruskal-Wallis rank sum test
## 
## data:  Total Charges by Customer Status
## Kruskal-Wallis chi-squared = 1402.2, df = 2, p-value < 2.2e-16

Interpretation of result

if (kruskal_result$p.value < 0.05) {
  cat("The Kruskal-Wallis test indicates a significant difference in Total Charges across Churn Status groups.\n")
} else {
  cat("There is no significant difference in Total Charges across Churn Status groups.\n")
}
## The Kruskal-Wallis test indicates a significant difference in Total Charges across Churn Status groups.

The results provided a highly significant p-value p< 2.2e-16 suggesting that there are signficant differences in total charges among tge different customer status groups.

Visualize results with boxplots

ggplot(telecom_data, aes(x = `Customer Status`, y = `Total Charges`)) +
  geom_boxplot(fill = "skyblue", color = "black") +
  labs(title = "Total Charges Across Churn Status", x = "`Customer Status`", y = "`Total Charges`")

Machine Learning Model for Customer Churn

Convert the outcome variable to a factor with three levels

telecom_data$`Customer Status` <- as.factor(telecom_data$`Customer Status`)

Split the data into training and testing sets

set.seed(123)
train_index <- createDataPartition(telecom_data$`Customer Status`, p = 0.7, list = FALSE)
train_data <- telecom_data[train_index, ]
test_data <- telecom_data[-train_index, ]

Build a multinomial logistic regression model

multinom_model <- multinom(`Customer Status` ~ `Total Charges`, data = train_data)
## # weights:  9 (4 variable)
## initial  value 3719.901209 
## iter  10 value 2197.419703
## final  value 2143.958917 
## converged

Make predictions on the test set

predictions <- predict(multinom_model, newdata = test_data, type = "class")

Evaluate the model

conf_matrix <- confusionMatrix(predictions, test_data$`Customer Status`)
print(conf_matrix)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction Churned Joined Stayed
##    Churned     234     53    133
##    Joined       29     17      0
##    Stayed      212      0    771
## 
## Overall Statistics
##                                           
##                Accuracy : 0.7053          
##                  95% CI : (0.6811, 0.7287)
##     No Information Rate : 0.6239          
##     P-Value [Acc > NIR] : 4.575e-11       
##                                           
##                   Kappa : 0.3863          
##                                           
##  Mcnemar's Test P-Value : NA              
## 
## Statistics by Class:
## 
##                      Class: Churned Class: Joined Class: Stayed
## Sensitivity                  0.4926       0.24286        0.8529
## Specificity                  0.8090       0.97897        0.6110
## Pos Pred Value               0.5571       0.36957        0.7843
## Neg Pred Value               0.7658       0.96222        0.7146
## Prevalence                   0.3278       0.04831        0.6239
## Detection Rate               0.1615       0.01173        0.5321
## Detection Prevalence         0.2899       0.03175        0.6784
## Balanced Accuracy            0.6508       0.61091        0.7319

Create a data frame for the confusion matrix

conf_matrix_df <- data.frame(
  Actual = rep(rownames(conf_matrix$byClass), each = ncol(conf_matrix$byClass)),
  Predicted = rep(colnames(conf_matrix$byClass), times = nrow(conf_matrix$byClass)),
  Freq = as.vector(conf_matrix$byClass)
)

Create a confusion matrix plot

A confusion matrix helps evaluate the performance of a classification model. In this context it is like a scoreboard that predicts different outcomes based on total charges.

ggplot(conf_matrix_df, aes(x = Actual, y = Predicted, fill = Freq)) +
  geom_tile(color = "white", stat = "identity") +
  scale_fill_gradient(low = "skyblue1", high = "lightcoral") +
  labs(title = "Confusion Matrix for Multinomial Logistic Regression",
       subtitle = "Predicted vs. Actual Churn Status",
       x = "Actual", y = "Predicted") +
  theme_minimal()