总结dplyr和rle的连续失败

问题描述 投票:3回答:1

我正在尝试建立一个流失模型,该模型包括每个客户遇到麻烦的最大连续UX故障数。这是我的简化数据和所需的输出:

library(dplyr)
df <- data.frame(customerId = c(1,2,2,3,3,3), date = c('2015-01-01','2015-02-01','2015-02-02', '2015-03-01','2015-03-02','2015-03-03'),isFailure = c(0,0,1,0,1,1))
> df
  customerId       date isFailure
1          1 2015-01-01         0
2          2 2015-02-01         0
3          2 2015-02-02         1
4          3 2015-03-01         0
5          3 2015-03-02         1
6          3 2015-03-03         1

所需结果:

> desired.df
  customerId maxConsecutiveFailures
1          1                      0
2          2                      1
3          3                      2

我感到非常困惑,并且搜索其他有关角色的问题仍无济于事-这就是我“期望”一个类似于的解决方案:

df %>% 
  group_by(customerId) %>%
  summarise(maxConsecutiveFailures = 
    max(rle(isFailure[isFailure == 1])$lengths))
r dplyr
1个回答
4
投票

我们通过'customerId'分组,并使用do在'isFailure'列上执行rle。提取lengthsvalues)为'TRUE'的lengths[values],并使用if/else条件创建'Max'列,以为没有任何1值的那些返回0。

 df %>%
    group_by(customerId) %>%
    do({tmp <- with(rle(.$isFailure==1), lengths[values])
     data.frame(customerId= .$customerId, Max=if(length(tmp)==0) 0 
                    else max(tmp)) }) %>% 
     slice(1L)
#   customerId Max
#1          1   0
#2          2   1
#3          3   2
© www.soinside.com 2019 - 2024. All rights reserved.