2017-02-21 75 views
1

我的客户评分数据如下:检查得分趋势

cust_id score_date score 
    1  5/1/2016 80 
    1  5/2/2016 83 
    1  5/22/2016 90 
    2  6/1/2016 92 
    2  7/2/2016 87 

,我要检查客户的得分趋势;这意味着,我想检查客户的分数是否随着时间的推移而增加(积极趋势)。

我想用这样的事情(与dplyr)的:

results <- df %>% 
      group_by(cust_id) %>% 
      .[order(-.[, 2]), ] 

,但我不太确定如何检查评分的差异。

我想我的答案设置为计数有积极趋势的客户数量;是这样的:

 positive_trend (number of customers) 
yes  1,000 
no   78 

您的帮助将不胜感激

+3

@akrun做到这一点你确定这是一个重复的?你的链接是一个简单的组/集合操作,而这里的问题要复杂得多,并涉及中间的计算步骤。 – Uwe

+0

@UweBlock你是对的。这有点复杂。删除了链接 – akrun

回答

2

使用dplyr。对于每个cust_id我们计算连续行与diff之间的差异,然后用summarise来计算正数和负数的数量。

library(dplyr) 
df %>% 
    group_by(cust_id) %>% 
    mutate(difference = c(0, diff(score))) %>% 
    summarise(yes = sum(difference > 0), 
      no = sum(difference < 0)) 


# cust_id yes no 
# <int> <int> <int> 
#1 1  2  0 
#2 2  0  1 

注意:根据此代码,每组中的第一行将被忽略,因为在开始时没有趋势。

1

我们可以data.table

library(data.table) 
setDT(df)[, as.list(table(factor(diff(score)>0, levels = c(TRUE, FALSE), 
           labels = c("yes", "no")))), cust_id] 
# cust_id yes no 
#1:  1 2 0 
#2:  2 0 1 

或者使用base R

table(transform(stack(with(df, tapply(score, cust_id, 
        FUN = diff)))[2:1], values = values > 0))