0

I have column names as timestamps like , 0:00:00 1:00:00 10:00:00 11:00:00 12:00:00 13:00:00 14:00:00.

As you can see timestamp 1:00:00 is followed by 10:00:00 instead of 02:00:00.

From digging on this topic , came across this problem sorting values in a dataframe and conversion of the data type of values as numeric was the solution.

How do we convert column names into numeric and sort the columns not the data?

Dave
  • 1
  • 1
  • 1
    Please provide a reproducible example with `dput`. This should be easy to achieve by converting to `datetime`, but it's easier to show with sample data – Julian_Hn Mar 30 '19 at 11:53
  • 1
    Please edit your **question** according to [this](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Thanks! – NelsonGon Mar 30 '19 at 11:55

1 Answers1

0

I've produced a sample dataset to illustrate my solution: Using lubridate we can convert the colnames to a time-format and then order the data.frame accordingly:

df <- structure(list(`0:00:00` = 1:9, `1:00:00` = 10:18, `10:00:00` = 19:27, 
    `11:00:00` = 28:36, `12:00:00` = 37:45, `13:00:00` = 46:54, 
    `14:00:00` = 55:63), .Names = c("0:00:00", "1:00:00", "10:00:00", 
"11:00:00", "12:00:00", "13:00:00", "14:00:00"), class = "data.frame", row.names = c(NA, 
-9L))

df2 <- structure(list(`0:00:00` = 1:9, `1:00:00` = 19:27, `10:00:00` = 28:36, 
    `11:00:00` = 10:18, `12:00:00` = 37:45, `13:00:00` = 46:54, 
    `14:00:00` = 55:63), .Names = c("0:00:00", "1:00:00", "10:00:00", 
"11:00:00", "12:00:00", "13:00:00", "14:00:00"), class = "data.frame", row.names = c(NA, 
-9L))

library(lubridate)
df <- df[,order(hms(names(df)))]
df2 <- df2[,order(hms(names(df2)))]
Julian_Hn
  • 2,086
  • 1
  • 8
  • 18
  • Thank you so much for the inputs, i tried for the following col names 0:00:00 1:00:00 10:00:00 11:00:00 12:00:00 13:00:00 14:00:00 02:00:00 03:00:00 and sorted the above column names to 0:00:00 1:00:00 02:00:00 03:00:00 10:00:00 11:00:00 12:00:00 13:00:00 14:00:00 – Dave Mar 31 '19 at 13:21