首页 > 解决方案 > 按r中的特定日期顺序分组

问题描述

我有一张订单表 | 地点 | 日期,如果每个订单在前一个订单的第二天(时差 <= 1 天),则希望在一行中对每个订单进行分组和计数。分组订单以显示较早的日期和实例计数。请看下面的例子。

输入:

| Order | Place | Date     |
|-------|-------|----------|
| 11    | A     | 01.11.19 |
| 11    | A     | 02.11.19 |
| 11    | A     | 05.11.19 |
| 22    | B     | 01.11.19 |
| 22    | D     | 02.11.19 |
| 22    | D     | 03.11.19 |
| 33    | A     | 01.11.19 |

输出:

| Order | Place | Date     | Count |
|-------|-------|----------|-------|
| 11    | A     | 01.11.19 | 2     |
| 11    | A     | 05.11.19 | 1     |
| 22    | B     | 01.11.19 | 1     |
| 22    | D     | 02.11.19 | 2     |
| 33    | A     | 01.11.19 | 1     |

标签: rdataframedifftime

解决方案


这是另一个使用的解决方案dplyr

library(dplyr)

df1 %>% 
  mutate(Date = as.Date(Date, "%d.%m.%y")) %>% 
  group_by(Order, Place, DateLag = !((Date - lag(Date, default = first(Date)))>1)) %>% 
  summarise(Date = first(Date), Count = n()) %>% 
  ungroup %>% select(-DateLag) %>% 
  arrange(Order, Place, Date)

># # A tibble: 5 x 4
>#   Order Place Date       Count
>#   <int> <chr> <date>     <int>
># 1    11 A     2019-11-01     2
># 2    11 A     2019-11-05     1
># 3    22 B     2019-11-01     1
># 4    22 D     2019-11-02     2
># 5    33 A     2019-11-01     1

数据:

read.table(text=" Order  Place  Date     
 11     A      01.11.19 
 11     A      01.11.19 
 11     A      05.11.19 
 22     B      01.11.19 
 22     D      02.11.19 
 22     D      03.11.19 
 33     A      01.11.19", header=T, stringsAsFactors=F) -> df1

推荐阅读