拥有以下数据框:
test <- data.frame(Brand = rep(c("A","B","C"),5), SaleDate =c("12.12.2013","29.6.2004","1.9.2011","16.6.2004","22.9.2011","25.12.2011","20.10.2011","13.1.2012","3.2.2012","29.8.2013","8.10.2013","3.8.2013","15.6.2004","24.7.2013","16.6.2004"))
我需要首先根据列#34; Brand&#34;对数据进行分组。然后根据列&#34; SaleDate&#34;对组进行排序。我需要转换列&#34; SaleDate&#34;进入日期进行基于日期的排序并获得:
Brand SaleDate
A 15.6.2004
A 16.6.2004
A 20.10.2011
A 29.8.2013
A 12.12.2013
B 29.6.2004
B 22.9.2011
B 13.1.2012
B 24.7.2013
B 8.10.2013
C 16.6.2004
C 1.9.2011
C 25.12.2011
C 3.2.2012
C 3.8.2013
这个问题可能已有答案,但我找不到。任何链接也将受到赞赏。
答案 0 :(得分:3)
首先将SaleDate
列转换为如此日期:
library('lubridate')
test$SaleDate <- dmy(test$SaleDate)
然后按Brand
和SaleDate
library('dplyr')
newtest <- arrange(test, Brand, SaleDate)
newtest
将如下所示(日期为YYYY-MM-DD)
> newtest
Brand SaleDate
1 A 2004-06-15
2 A 2004-06-16
3 A 2011-10-20
4 A 2013-08-29
5 A 2013-12-12
6 B 2004-06-29
7 B 2011-09-22
8 B 2012-01-13
9 B 2013-07-24
10 B 2013-10-08
11 C 2004-06-16
12 C 2011-09-01
13 C 2011-12-25
14 C 2012-02-03
15 C 2013-08-03