user11418708
user11418708

Reputation: 902

Reorder the rows of a dataframe

I would like to reorder my df time column to start from 04:00 and not from 00:00. The order will be 04:00, 05:00,...,00:00, 01:00, 02:00, 03:00 be How can I do this?

<-structure(list(time=c ("00:00", "01:00","02:00","03:00", "04:00", "05:00", "06:00", "07:00",
                        "08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00",
                         "19:00", "20:00", "21:00", "22:00", "23:00"), 
               Season = c(1, 2, 3, 5, 6, 7,8,9,10,12,1,1, 2, 3, 5, 6, 7,8,9,10,12,9,10,12), 
               Total= c(1, 2, 3, 5, 6, 7,8,9,10,12,1,1, 2, 3, 5, 6, 7,8,9,10,12,9,10,12 ) 
              ), row.names = c(NA,24L), class = "data.frame")

Upvotes: 0

Views: 52

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388797

You can use match to find the index of '04:00' :

inds <- match('04:00', df$time)
df[c(inds:nrow(df), 1:(inds - 1)), ]

#    time Season Total
#5  04:00      6     6
#6  05:00      7     7
#7  06:00      8     8
#8  07:00      9     9
#9  08:00     10    10
#10 09:00     12    12
#11 10:00      1     1
#...
#...
#1  00:00      1     1
#2  01:00      2     2
#3  02:00      3     3
#4  03:00      5     5

Here is another variation with dplyr :

library(dplyr)
df %>% arrange(row_number() < match('04:00', time))

Upvotes: 1

Related Questions