r - 按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 |
解决方案
这是另一个使用的解决方案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
推荐阅读
- bash - 在 sqlite3 中显示多行消息
- javascript - 递归遍历后返回一个新对象
- python-3.x - 使用 BeautifulSoup 找不到特定表
- python-3.x - pytest & pytest-benchmark:串行还是并行?
- docusignapi - Docusign 不允许我将收件人添加到模板
- ruby-on-rails - 如何按点顺序列出
- python - 如何在多个文件上运行脚本python
- mysql - 如何在第二列的值可以是任何值的多个列上执行选择
- javascript - 如何根据属性过滤 csvLayer?
- javascript - 从 Firebase 查询数组(React Native)