首页 > 解决方案 > 计算 R 中一列的保留率

问题描述

我需要您的建议,因为我正在努力在 R 中找到正确的命令。

基本上我想计算特定客户的保留率。customer_math 是客户活跃时间的快照,包括 8 年的时间范围。

customer  customer_math
Apple          1
Tesco          10
Nespresso      1001
Dell           11
BMW            11111100

最终数据集应如下所示:

customer  customer_math      retention_rate
Apple          1                1
Tesco          10               0.5
Nespresso      1001             0.5
Dell           11               1
BMW            11111100         0.75

关于如何解决我的问题的任何想法?

非常感谢您的帮助!谢谢!

标签: rdplyrchurn

解决方案


您可以删除字符串中的所有 0,计算nchar并除以 total nchar

df$retention_rate <- with(df, nchar(gsub('0', '', customer_math, fixed = TRUE))/
                              nchar(customer_math))
df
#   customer customer_math retention_rate
#1     Apple             1           1.00
#2     Tesco            10           0.50
#3 Nespresso          1001           0.50
#4      Dell            11           1.00
#5       BMW      11111100           0.75

数据

df <- structure(list(customer = structure(c(1L, 5L, 4L, 3L, 2L), 
.Label = c("Apple", "BMW", "Dell", "Nespresso", "Tesco"), class = "factor"), 
customer_math = c(1L, 10L, 1001L, 11L, 11111100L)), class = "data.frame", 
row.names = c(NA, -5L))

推荐阅读