{"id":3005,"date":"2024-10-13T22:09:14","date_gmt":"2024-10-13T13:09:14","guid":{"rendered":"https:\/\/secondlife.lol\/?p=3005"},"modified":"2024-10-15T17:56:22","modified_gmt":"2024-10-15T08:56:22","slug":"kaplan-meier-survival-analysis-r-intro","status":"publish","type":"post","link":"https:\/\/secondlife.lol\/en\/kaplan-meier-survival-analysis-r-intro\/","title":{"rendered":"Survival Analysis? It's Not That Hard! Understanding Kaplan-Meier Models in R: A Quick Guide"},"content":{"rendered":"<p class=\"wp-block-paragraph\">Have you ever heard of survival analysis? It may seem intimidating when you first hear it, but it's actually not that complicated. Today, we're going to show you how to do it with the <strong><a href=\"https:\/\/www.ibm.com\/docs\/ko\/spss-statistics\/saas?topic=statistics-kaplan-meier-survival-analysis\" target=\"_blank\" rel=\"noopener\">Kaplan-Meier survival analysis model<\/a>An Easy Introduction to R<\/strong>I'm going to try it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">While survival analysis is often used in life science or medical research, <strong>Customer churn analysis<\/strong>or <strong>Product lifetime<\/strong>is also a powerful tool that is often used to measure outcomes. Let's take the Kaplan-Meier model, the classic model for survival analysis, as an example.<\/p>\n\n\n<style>.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-content-wrap{padding-top:var(--global-kb-spacing-sm, 1.5rem);padding-right:var(--global-kb-spacing-sm, 1.5rem);padding-bottom:var(--global-kb-spacing-sm, 1.5rem);padding-left:var(--global-kb-spacing-sm, 1.5rem);border-top:3px solid var(--global-palette2, #2B6CB0);border-right:3px solid var(--global-palette2, #2B6CB0);border-bottom:3px solid var(--global-palette2, #2B6CB0);border-left:3px solid var(--global-palette2, #2B6CB0);border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-right-radius:5px;border-bottom-left-radius:5px;box-shadow:0px 0px 14px 0px rgba(0, 0, 0, 0.2);}.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-contents-title-wrap{padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;}.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-contents-title-wrap{color:var(--global-palette2, #2B6CB0);}.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-contents-title{color:var(--global-palette2, #2B6CB0);font-size:28px;font-weight:regular;font-style:normal;}.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-content-wrap .kb-table-of-content-list{color:var(--global-palette1, #3182CE);line-height:2em;font-weight:regular;font-style:normal;margin-top:var(--global-kb-spacing-sm, 1.5rem);margin-right:0px;margin-bottom:0px;margin-left:0px;}.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-content-wrap .kb-table-of-content-list .kb-table-of-contents__entry:hover{color:var(--global-palette6, #718096);}@media all and (max-width: 1024px){.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-content-wrap{border-top:3px solid var(--global-palette2, #2B6CB0);border-right:3px solid var(--global-palette2, #2B6CB0);border-bottom:3px solid var(--global-palette2, #2B6CB0);border-left:3px solid var(--global-palette2, #2B6CB0);}}@media all and (max-width: 1024px){.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-contents-title{font-size:28px;}}@media all and (max-width: 767px){.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-content-wrap{border-top:3px solid var(--global-palette2, #2B6CB0);border-right:3px solid var(--global-palette2, #2B6CB0);border-bottom:3px solid var(--global-palette2, #2B6CB0);border-left:3px solid var(--global-palette2, #2B6CB0);}.kb-table-of-content-nav.kb-table-of-content-id83_5f28a6-34 .kb-table-of-contents-title{font-size:28px;}}<\/style>\n\n\n<h2 class=\"wp-block-heading\">What is Kaplan-Meier survival analysis?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Survival analysis compares the effect of <strong>Events (e.g., going out of business, churn, death, etc.)<\/strong>This model allows you to analyze the time until a specific event occurs. For example, <strong>The probability of a customer churning your service<\/strong>or <strong>How long until the product fails<\/strong>to measure the<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Kaplan-Meier model creates a survival curve and uses the <strong>The likelihood of an event occurring over time<\/strong>as a visual representation. Every time this curve falls, it means an event has occurred.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Learn the Kaplan-Meier model with an easy example<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now, let's look at an easy example that you can apply in real life. <strong>Customer churn analysis<\/strong>For example, we can assume that we have 10 customers using our service. How many of them will continue to use the service and how many will churn? We can use the Kaplan-Meier model to analyze the probability of churn.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We'll use R code to visualize this process.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Load the required library\nlibrary(survival)\nlibrary(survminer)\n\n# Create data for 10 customers\n# Record the years customers used your service and the years they churned\ndata &lt;- data.frame(\n    customer = 1:10,\n    start_year = rep(2020, 10), # All customers started using the service in 2020\n    leave_year = c(2021, NA, 2022, NA, 2023, 2024, NA, NA, 2023, 2024) # If they didn&#039;t leave, NA\n)\n\n# Calculate how long the customer has been using the service\ndata$time_in_service &lt;- ifelse(is.na(data$leave_year), 2024 - data$start_year, data$leave_year - data$start_year)\n\n# Show whether a customer has churned or not as a 1 or 0 (1: churned, 0: still using)\ndata$status &lt;- ifelse(is.na(data$leave_year), 0, 1)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Code description:<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Generate data<\/strong>: Create data for 10 customers who started using your service in 2020. Some customers start churning in 2021, while others are still using the service.<\/li>\n\n\n\n<li><strong>Calculate churn periods<\/strong>Calculate how many years each customer has used the service. Customers who have not churned are considered to have used the service until 2024.<\/li>\n\n\n\n<li><strong>Bounce or not<\/strong>: Displays whether the customer has churned, as 1 (churned) and 0 (still using).<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Visualize Kaplan-Meier survival curves<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now let's plot a Kaplan-Meier survival curve based on our data. We'll create a curve that visually represents how long customers have been using our service.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Apply a # Kaplan-Meier survival model\nfit &lt;- survfit(Surv(time_in_service, status) ~ 1, data = data)\n\nVisualize the # survival curve (passing the data explicitly)\nggsurvplot(fit,\n           data = data, # Pass data to ggsurvplot\n           conf.int = TRUE, # Show confidence intervals\n           xlab = &quot;Length of time using the service (years)&quot;, # label x-axis\n           ylab = &quot;Percentage of customers using the service&quot;, # y-axis label\n           title = &quot;Survival curve of customers using the service&quot;, # graph title\n           palette = &quot;blue&quot;, # Graph color\n           risk.table = TRUE, # Add risk table for each year\n           ggtheme = theme_minimal()) # Apply minimal theme<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Code description:<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Apply the Kaplan-Meier model<\/strong>Calculate the probability of churn by applying a Kaplan-Meier survival model to customer data.<\/li>\n\n\n\n<li><strong>Visualize survival curves<\/strong>: <code>ggsurvplot<\/code> Use a function to draw a survival curve for a customer based on how long they've been using your service. <code>conf.int = TRUE<\/code>indicates a confidence interval to increase the confidence in the result.<\/li>\n\n\n\n<li><strong>Add a risk table<\/strong>: Add a table below the graph that shows the number of customers using the service in each year.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Interpreting visualization results<\/h2>\n\n\n<style>.kb-image3005_40e803-c7 .kb-image-has-overlay:after{opacity:0.3;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-right-radius:5px;border-bottom-left-radius:5px;}.kb-image3005_40e803-c7 img.kb-img, .kb-image3005_40e803-c7 .kb-img img{border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-right-radius:5px;border-bottom-left-radius:5px;box-shadow:0px 0px 14px 0px rgba(0, 0, 0, 0.2);}<\/style>\n<div class=\"wp-block-kadence-image kb-image3005_40e803-c7\"><figure class=\"aligncenter size-full\"><img decoding=\"async\" width=\"1200\" height=\"613\" src=\"https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-1-26.jpg\" alt=\"Kaplan-Meier \uc0dd\uc874 \ubd84\uc11d \uc2dc\uac01\ud654\" class=\"kb-img wp-image-3006\" srcset=\"https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-1-26.jpg 1200w, https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-1-26-300x153.jpg 300w, https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-1-26-600x307.jpg 600w, https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/image-1-26-768x392.jpg 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">1. Survival curve overview<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>This graph shows the survival curve of customers using your service.<\/li>\n\n\n\n<li><strong>x-Axis<\/strong>indicates how long you've been using the service (in years), <strong>y-Axis<\/strong>represents the percentage of customers still using the service.<\/li>\n\n\n\n<li>Initially, all customers (100%) are using the service, and over time, the survival curve steps down as customers churn.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">2. key points on the curve<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The graph is a <strong>0 \u5e74<\/strong>and initially shows that all customers (10) are using the service.<\/li>\n\n\n\n<li><strong>1 year<\/strong>and the first churn occurs, at which point the survival curve shifts from 100% to about <strong>90%<\/strong>in the list.<\/li>\n\n\n\n<li><strong>2 years<\/strong>then churn will occur again, causing the survival curve to drop to <strong>About 80%<\/strong>in the list.<\/li>\n\n\n\n<li><strong>3 years<\/strong> Since then, the survival curve has dropped again, <strong>60%<\/strong>of customers remain and continue to use the service.<\/li>\n\n\n\n<li><strong>4 years<\/strong> At that point, the survival curve drops further, finally reaching around <strong>50%<\/strong>is the only customer left.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">3. confidence intervals (shades of gray)<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Around the blue survival curve <strong>Shades of gray<\/strong>is <strong>Confidence Interval<\/strong>to indicate the<\/li>\n\n\n\n<li>This shows the confidence in the survival probability at each point, with wider shading indicating greater uncertainty in the prediction.<\/li>\n\n\n\n<li>The confidence interval widens with each downward slope of the survival curve, increasing the uncertainty of the prediction over time.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">4. Number at Risk table<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>At the bottom of the graph is a table called \"Number at Risk\".<\/li>\n\n\n\n<li>This table shows the number of customers still using the service for each year.<\/li>\n\n\n\n<li><strong>0 \u5e74<\/strong> At this point, all 10 customers are using the service.<\/li>\n\n\n\n<li><strong>1 year<\/strong> Afterward, there are 9 customers left, <strong>2 years<\/strong> Later, 8 people, <strong>3 years<\/strong> Later, 6 people are still using the service.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">5. Interpret Curves<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Falling survival curve<\/strong>The downward sloping part of the curve indicates that customers have abandoned the service. The longer a service is used, the more customers churn, and the survival curve gradually declines.<\/li>\n\n\n\n<li><strong>Last survival rate<\/strong>: After four years, half (50%) of the customers are still using the service, meaning the other 50% have churned.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This graph visually shows how long customers stay with your service and how they tend to churn using Kaplan-Meier survival analysis. You can get a clear picture of the percentage of customers who churn over time.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Recap: Kaplan-Meier Model R Analysis, No Longer Difficult!<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Today we demystified the Kaplan-Meier survival analysis model and even visualized it ourselves using R. This model may seem intimidating at first, but it becomes much easier to understand when applied to a real-world example like customer churn analysis. We hope you'll use this model for a variety of data analysis in the future!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Copy the entire code below at once and add it to the <a href=\"https:\/\/secondlife.lol\/en\/r-rstudio-install\/\" data-type=\"post\" data-id=\"454\">RStudio<\/a>If you're curious to see a real-world application of this Kaplan-Meier model, you can find it in the <a href=\"https:\/\/secondlife.lol\/en\/black-and-white-chef-michelin-curse-r-analysis\/\" data-type=\"post\" data-id=\"2995\">The Michelin curse that even black-and-white chefs can't escape: the story analyzed in R<\/a> We hope you'll review the post.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">#Full R code<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code># Load the required library\nlibrary(survival)\nlibrary(survminer)\n\n# Create data for 10 customers\n# Record the years customers used your service and the years they churned\ndata &lt;- data.frame(\n    customer = 1:10,\n    start_year = rep(2020, 10), # All customers started using the service in 2020\n    leave_year = c(2021, NA, 2022, NA, 2023, 2024, NA, NA, 2023, 2024) # If they didn&#039;t leave, NA\n)\n\n# Calculate how long the customer has been using the service\ndata$time_in_service &lt;- ifelse(is.na(data$leave_year), 2024 - data$start_year, data$leave_year - data$start_year)\n\n# Show whether a customer has churned or not as a 1 or 0 (1: churned, 0: still using)\ndata$status &lt;- ifelse(is.na(data$leave_year), 0, 1)\n\nApply a # Kaplan-Meier survival model\nfit &lt;- survfit(Surv(time_in_service, status) ~ 1, data = data)\n\nVisualize the # survival curve (passing the data explicitly)\nggsurvplot(fit,\n           data = data, # Pass data to ggsurvplot\n           conf.int = TRUE, # Show confidence intervals\n           xlab = &quot;Length of time using the service (years)&quot;, # label x-axis\n           ylab = &quot;Percentage of customers using the service&quot;, # y-axis label\n           title = &quot;Survival curve of customers using the service&quot;, # graph title\n           palette = &quot;blue&quot;, # Graph color\n           risk.table = TRUE, # Add risk table for each year\n           ggtheme = theme_minimal()) # Apply minimal theme\n<\/code><\/pre>","protected":false},"excerpt":{"rendered":"<p>Have you ever heard of survival analysis? It can seem daunting when you first hear it...<\/p>","protected":false},"author":3,"featured_media":3009,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_kad_blocks_custom_css":"","_kad_blocks_head_custom_js":"","_kad_blocks_body_custom_js":"","_kad_blocks_footer_custom_js":"","_kad_post_transparent":"","_kad_post_title":"","_kad_post_layout":"","_kad_post_sidebar_id":"","_kad_post_content_style":"","_kad_post_vertical_padding":"","_kad_post_feature":"","_kad_post_feature_position":"","_kad_post_header":false,"_kad_post_footer":false,"_kad_post_classname":"","footnotes":""},"categories":[6],"tags":[384,300,385,177,382],"class_list":["post-3005","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-r-coding","tag-kaplan-meier-","tag-r-","tag-385","tag-177","tag-382"],"taxonomy_info":{"category":[{"value":6,"label":"\uc54c(R)"}],"post_tag":[{"value":384,"label":"Kaplan-Meier \ubaa8\ub378"},{"value":300,"label":"R \uc2dc\uac01\ud654"},{"value":385,"label":"\uace0\uac1d \uc774\ud0c8 \ubd84\uc11d"},{"value":177,"label":"\ub370\uc774\ud130 \ubd84\uc11d"},{"value":382,"label":"\uc0dd\uc874 \ubd84\uc11d"}]},"featured_image_src_large":["https:\/\/secondlife.lol\/wp-content\/uploads\/2024\/10\/\uc0dd\uc874-\ubd84\uc11d-\ubaa8\ub378-\ud3ec\uc2a4\ud2b8-\uc378\ub124\uc77c-600x600.jpg",600,600,true],"author_info":{"display_name":"TERE","author_link":"https:\/\/secondlife.lol\/en\/author\/tere\/"},"comment_info":0,"category_info":[{"term_id":6,"name":"\uc54c(R)","slug":"r-coding","term_group":0,"term_taxonomy_id":6,"taxonomy":"category","description":"","parent":20,"count":61,"filter":"raw","cat_ID":6,"category_count":61,"category_description":"","cat_name":"\uc54c(R)","category_nicename":"r-coding","category_parent":20}],"tag_info":[{"term_id":384,"name":"Kaplan-Meier \ubaa8\ub378","slug":"kaplan-meier-%eb%aa%a8%eb%8d%b8","term_group":0,"term_taxonomy_id":384,"taxonomy":"post_tag","description":"","parent":0,"count":1,"filter":"raw"},{"term_id":300,"name":"R \uc2dc\uac01\ud654","slug":"r-%ec%8b%9c%ea%b0%81%ed%99%94","term_group":0,"term_taxonomy_id":300,"taxonomy":"post_tag","description":"","parent":0,"count":12,"filter":"raw"},{"term_id":385,"name":"\uace0\uac1d \uc774\ud0c8 \ubd84\uc11d","slug":"%ea%b3%a0%ea%b0%9d-%ec%9d%b4%ed%83%88-%eb%b6%84%ec%84%9d","term_group":0,"term_taxonomy_id":385,"taxonomy":"post_tag","description":"","parent":0,"count":1,"filter":"raw"},{"term_id":177,"name":"\ub370\uc774\ud130 \ubd84\uc11d","slug":"%eb%8d%b0%ec%9d%b4%ed%84%b0-%eb%b6%84%ec%84%9d","term_group":0,"term_taxonomy_id":177,"taxonomy":"post_tag","description":"","parent":0,"count":36,"filter":"raw"},{"term_id":382,"name":"\uc0dd\uc874 \ubd84\uc11d","slug":"%ec%83%9d%ec%a1%b4-%eb%b6%84%ec%84%9d","term_group":0,"term_taxonomy_id":382,"taxonomy":"post_tag","description":"","parent":0,"count":2,"filter":"raw"}],"_links":{"self":[{"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/posts\/3005","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/comments?post=3005"}],"version-history":[{"count":2,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/posts\/3005\/revisions"}],"predecessor-version":[{"id":3028,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/posts\/3005\/revisions\/3028"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/media\/3009"}],"wp:attachment":[{"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/media?parent=3005"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/categories?post=3005"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/secondlife.lol\/en\/wp-json\/wp\/v2\/tags?post=3005"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}