shirleywu
shirleywu

Reputation: 674

How do I order a data frame by ID, date, then time?

I have this in R, and I want to put each ID number next to each other and then sort by Date, finally by Time... Is this possible?

   ID Val      Date  Time
1   1 0.7 1/13/2013 12:00
2   2 1.6 1/13/2013 12:00
3   3 0.5 1/13/2013 12:00
4   4 2.1 1/13/2013 12:00
5   5 1.2 1/13/2013 12:00
6   1 1.0 1/13/2013 13:00
7   2 1.1 1/13/2013 13:00
8   3 0.9 1/13/2013 13:00
9   4 2.4 1/13/2013 13:00
10  5 0.8 1/13/2013 13:00

Upvotes: 2

Views: 9458

Answers (2)

Jilber Urbina
Jilber Urbina

Reputation: 61214

orderBy from doBy package is another alternative:

> library(doBy)
> orderBy(~ID+Date+Time, data=DF)

Upvotes: 4

Sacha Epskamp
Sacha Epskamp

Reputation: 47642

order can take multiple arguments to do just this:

df <- read.table(text="ID Val      Date  Time
1   1 0.7 1/13/2013 12:00
2   2 1.6 1/13/2013 12:00
3   3 0.5 1/13/2013 12:00
4   4 2.1 1/13/2013 12:00
5   5 1.2 1/13/2013 12:00
6   1 1.0 1/13/2013 13:00
7   2 1.1 1/13/2013 13:00
8   3 0.9 1/13/2013 13:00
9   4 2.4 1/13/2013 13:00
10  5 0.8 1/13/2013 13:00",header=TRUE)


df[with(df,order(ID,Date,Time)),]

Note that I didn't yet convert Date and Time to appropriate time classes yet here, which wil give better results.

Upvotes: 6

Related Questions