2017-05-27 9 views
1

私は人がトランザクションを作るときには、私に語っローリング関数を別の列に分割して実装するにはどうすればよいですか?

CustomerID   InvoiceDate 
     <fctr>    <dttm> 
1  13313 2011-01-04 10:00:00 
2  18097 2011-01-04 10:22:00 
3  16656 2011-01-04 10:23:00 
4  16875 2011-01-04 10:37:00 
5  13094 2011-01-04 10:37:00 
6  17315 2011-01-04 10:38:00 
7  16255 2011-01-04 11:30:00 
8  14606 2011-01-04 11:34:00 
9  13319 2011-01-04 11:40:00 
10  16282 2011-01-04 11:42:00 

のように見えるいくつかのデータを持っています。私は各顧客の取引の間、好ましくは日数を知りたいと思います。私は、しかし、結果は(下見て)

CustomerID   InvoiceDate delta.t delta.day 
     <fctr>    <dttm>  <time>  <dbl> 
1  12415 2011-01-10 09:58:00 5686 days  5686 
2  12415 2011-02-15 09:52:00 51834 days  51834 
3  12415 2011-03-03 10:59:00 23107 days  23107 
4  12415 2011-04-01 14:28:00 41969 days  41969 
5  12415 2011-05-17 15:42:00 66314 days  66314 
6  12415 2011-05-20 14:13:00 4231 days  4231 
7  12415 2011-06-15 13:37:00 37404 days  37404 
8  12415 2011-07-13 15:30:00 40433 days  40433 
9  12415 2011-07-13 15:31:00  1 days   1 
10  12415 2011-07-19 10:51:00 8360 days  8360 

日に測定した違いが道オフになっている意味がありません、次のよう

d <- data %>% 
    arrange(CustomerID,InvoiceDate) %>% 
    group_by(CustomerID) %>% 
    mutate(delta.t = InvoiceDate - lag(InvoiceDate), #calculating the difference 
      delta.day = as.numeric(delta.t, unit = 'days')) %>% 
    na.omit() %>% 
    arrange(CustomerID) %>% 
    inner_join(Ntrans) %>% #Existing data.frame telling me the number of transactions per customer 
    filter(N>=10) %>% #only want people with more than 10 transactions 
    select(-N) 

でこれを行います。私が望むのは、SQLのローリングウィンドウ関数がcustomerIDに分割されたものです。これをどのように実装できますか?

+1

delta.tは、数日ではなく数分で結果を出すようです。行8と行9の違いを参照してください。 –

+0

ああ、それはとても奇妙です。 –

+0

delta.tは、InvoiceDateのクラスがPOSIXctのときにうまく動作します –

答えて

0

パッケージの潤滑剤を使用することで、日差を変更したい場合にのみ使用できます。

> library('lubridate') 
> library('dplyr') 
> 
> InvoiceDate <- c('2011-01-10 09:58:00', '2011-02-15 09:52:00', '2011-03-03 10:59:00') 
> CustomerID <- c(111, 111, 111) 
> 
> dat <- data.frame('Invo' = InvoiceDate, 'ID' = CustomerID) 
> 
> dat %>% mutate('Delta' = as_date(Invo) - as_date(lag(Invo))) 
       Invo ID Delta 
1 2011-01-10 09:58:00 111 NA days 
2 2011-02-15 09:52:00 111 36 days 
3 2011-03-03 10:59:00 111 16 days 
関連する問題