amitbisai
amitbisai

Reputation: 143

Sort columns of a dataframe by column name as Date

Similar issue is handled in the question link I have the data frame with dates as column name.

test = data.frame("01-Apr-16" = c(0, 2, 4, 7, 8), 
                  "01-Jan-16" = c(4, 2, 4, 7, 8), 
                  "01-Dec-16" = c(1, 3, 8, 3, 2))

I have converted the dates to corresponding number formats

new_names = apply(data.frame(names(test)), 1, function(x) as.Date(strptime(x,format = "%d-%b-%y")))
colnames(test) = new_names  

The solution provided test[ , order(names(test))] doesn't works. Is there a efficient solution to the problem.

I have read the dataframe from an external .csv file, which retains the original format of dates in the column names.

Upvotes: 0

Views: 388

Answers (1)

Sotos
Sotos

Reputation: 51592

You don't need to apply,

i1 <- as.Date(names(test), format = 'X%d.%b.%y')
test[order(i1)]

which gives,

  X01.Jan.16 X01.Apr.16 X01.Dec.16
1          4          0          1
2          2          2          3
3          4          4          8
4          7          7          3
5          8          8          2

Upvotes: 3

Related Questions