简体   繁体   中英

Group and next sort based on different columns of data frame in R

Having following data frame:

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"))

I need to first group the data based on column "Brand" and then sort the groups based on column "SaleDate". I need to convert the column "SaleDate" into Date for sorting based on date and obtain this:

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

There might be already answers for this question but I could not find it. Any links would be appreciated as well.

First convert the SaleDate column to dates like so:

library('lubridate')
test$SaleDate <- dmy(test$SaleDate)

Then arrange in descending order by Brand and SaleDate

library('dplyr')
newtest <- arrange(test, Brand, SaleDate)

newtest will look like this (dates in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM