Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a data frame by date

I need to sort a data frame by date in R. The dates are all in the form of "dd/mm/yyyy". The dates are in the 3rd column. The column header is V3. I have seen how to sort a data frame by column and I have seen how to convert the string into a date value. I can't combine the two in order to sort the data frame by date.

like image 589
John Avatar asked Jun 05 '11 22:06

John


People also ask

How do you sort a data frame by date?

One thing to notice here is our DataFrame gets sorted in ascending order of dates, to sort the DataFrame in descending order we can pass an additional parameter inside the sort_values() function that will set ascending value to False and will return the DataFrame in descending order.

How do I sort a DataFrame by date in R?

Here order() function is used to sort the dataframe by R using order() function based on the date column, we have to convert the date column to date with the format, this will sort in ascending order.

How do you sort data by date in python?

To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object.


2 Answers

Assuming your data frame is named d,

d[order(as.Date(d$V3, format="%d/%m/%Y")),] 

Read my blog post, Sorting a data frame by the contents of a column, if that doesn't make sense.

like image 170
I82Much Avatar answered Oct 18 '22 08:10

I82Much


Nowadays, it is the most efficient and comfortable to use lubridate and dplyr libraries.

lubridate contains a number of functions that make parsing dates into POSIXct or Date objects easy. Here we use dmy which automatically parses dates in Day, Month, Year formats. Once your data is in a date format, you can sort it with dplyr::arrange (or any other ordering function) as desired:

d$V3 <- lubridate::dmy(d$V3) dplyr::arrange(d, V3) 
like image 29
Love-R Avatar answered Oct 18 '22 09:10

Love-R