9

I have some data that has to be formatted as (%d/%m/%Y). The data is out of chronological order because it is sorted by the first number which is the day, not the month.

I'm hoping I can specify to order or reorder that I want the sorting to happen differently. I'm just not sure how to do this.

Here is some date data to be ordered:

date
1/1/2009  
1/1/2010
1/1/2011
5/4/2009
5/4/2011
10/2/2009
10/3/2011
15/9/2010
15/3/2009
31/12/2011
31/7/2009

Thanks for any suggestions.

4

3 回答 3

11

按列排序时date将其转换为日期格式。

df[order(as.Date(df$date,format="%d/%m/%Y")),,drop=FALSE]
         date
1    1/1/2009
6   10/2/2009
9   15/3/2009
4    5/4/2009
11  31/7/2009
2    1/1/2010
8   15/9/2010
3    1/1/2011
7   10/3/2011
5    5/4/2011
10 31/12/2011
于 2013-07-25T17:16:19.423 回答
10

在 plyr 和 lubridate 的帮助下,这更容易:

library(lubridate)
library(plyr)

df <- read.csv(text = "date
1/1/2009  
1/1/2010
1/1/2011
5/4/2009
5/4/2011
10/2/2009
10/3/2011
15/9/2010
15/3/2009
31/12/2011
31/7/2009", stringsAsFactors = FALSE)

# Convert variable to date    
df$date <- dmy(df$date)
arrange(df, date)
# Or for descending order
arrange(df, desc(date))
于 2013-07-26T13:34:26.993 回答
0

丑陋但似乎有效:

date[order(sapply(strsplit(date, "/"), 
                  function(x) { paste(x[3], sprintf("%02d", as.integer(x[1])), 
                                            sprintf("%02d", as.integer(x[2])), 
                                            sep="") 
                              }
                 )
          )
    ]
于 2013-07-25T17:24:55.720 回答