Skip to content

Instantly share code, notes, and snippets.

@wlinInspire
Last active August 19, 2019 03:28
Show Gist options
  • Save wlinInspire/82b39691af693f860b2eaf5f3a6e3e0a to your computer and use it in GitHub Desktop.
Save wlinInspire/82b39691af693f860b2eaf5f3a6e3e0a to your computer and use it in GitHub Desktop.
Calculating Life Time Value for Subscription Products
library(survival)
library(data.table)
library(ggplot2)
data <- fread('https://raw.githubusercontent.com/IBM/invoke-wml-using-cognos-custom-control/master/data/Telco-Customer-Churn.csv')
churn_data <- data[, .(churn_flag = ifelse(Churn == 'Yes', 1, 0), tenure)]
km_curve <- survfit(Surv(tenure, churn_flag) ~ 1, data=churn_data)
# Calculate Survival and Churn Rate
km_curve_df = summary(km_curve)
# Plot Survival Curve
autoplot(km_curve) +
xlab('cycle') +
ylab('survival_rate') +
theme_minimal()
# Plot Attrition Curve
curve <- data.table(cycle = km_curve_df$time,
survival_rate = km_curve_df$surv,
churn_rate = km_curve_df$n.event / km_curve_df$n.risk)
ggplot(curve) +
geom_line(aes(cycle, churn_rate)) +
scale_y_continuous(labels = scales::percent) +
xlab('cycle') +
ylab('churn_rate') +
theme_minimal()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment