-2

I have a dataframe with 40 columns in it and I want to sort from smalled to largest on the "delay" column. What is the best way?

As an example I have a data frame below with 4 rows and a "delay" column:

  col1<-c(1,2,4,5)
  col2<-c(5,6,7,4)
  posX1<-as.POSIXct(c("2014-11-10 19:47:09","2014-11-10 19:59:49","2014-11-10 20:19:18","2014-11-10 20:59:25"))
  posX2<-as.POSIXct("2014-11-10 20:59:25")
  dif<-abs(posX1 - posX2)
  data.frame(col1 = col1, col2=col2,time=posX1,delay=dif)

 col1 col2                time     delay
1    1    5 2014-11-10 19:47:09 4336 secs
2    2    6 2014-11-10 19:59:49 3576 secs
3    4    7 2014-11-10 20:19:18 2407 secs
4    5    4 2014-11-10 20:59:25    0 secs

How do I sort from smallest to largest of the delay column?

Thank you!

user3022875
  • 8,598
  • 26
  • 103
  • 167

1 Answers1

1

First, I suggest to use data.table instead of data.frame because of its speed. if you use data.table then it is supper easy:

> A = data.table(col1 = col1, col2=col2,time=posX1,delay=dif)
> setkey(A,"delay")
> A
   col1 col2                time     delay
1:    5    4 2014-11-10 20:59:25    0 secs
2:    4    7 2014-11-10 20:19:18 2407 secs
3:    2    6 2014-11-10 19:59:49 3576 secs
4:    1    5 2014-11-10 19:47:09 4336 secs

If you insist to use data.frame, then use this:

> A = data.frame(col1 = col1, col2=col2,time=posX1,delay=dif)
> A[order(A$delay),]
  col1 col2                time     delay
4    5    4 2014-11-10 20:59:25    0 secs
3    4    7 2014-11-10 20:19:18 2407 secs
2    2    6 2014-11-10 19:59:49 3576 secs
1    1    5 2014-11-10 19:47:09 4336 secs
Mahdi Jadaliha
  • 1,947
  • 1
  • 14
  • 22