【问题标题】:How can I implement a rolling function partitioned over another column?如何实现在另一列上分区的滚动功能?
【发布时间】:2017-05-28 15:07:59
【问题描述】:

我有一些看起来像的数据

 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

它告诉我一个人何时进行交易。我想知道每个客户的交易之间的时间,最好以天为单位。我通过以下方式做到这一点

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)

但是,结果没有意义(见下文)

 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

以天为单位测量的差异相差甚远。我想要的是接近 SQL 的滚动窗口函数的东西,它通过 customerID 分区。我该如何实现?

【问题讨论】:

  • 似乎 delta.t 在几分钟内而不是几天内给出结果。查看第 8 行和第 9 行的区别。
  • 哦,太奇怪了。
  • delta.t 在 InvoiceDate 类为 POSIXct 时对我很有效

标签: r dplyr


【解决方案1】:

如果您只想将差异更改为天数,您可以使用包 lubridate。

  > 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多