2017-02-21 101 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))