There are two easy ways to sort a data frame by date in R:
Method 1: User order() from base R
#sort from least recent to most recent df[order(as.Date(df$date, format="%m/%d/%Y")),] #sort from most recent to least recent df[rev(order(as.Date(df$date, format="%m/%d/%Y"))),]
Method 2: Use functions from the lubridate and dplyr packages
library(lubridate) library(dplyr) #sort from least recent to most recent df %>% arrange(mdy(df$date)) #sort from most recent to least recent df %>% arrange(desc(mdy(df$date)))
This tutorial shows an example of how to use each of these methods in practice.
Method 1: Use order() from base R
The most basic way to sort a data frame by a date variable in R is to use the order() function from base R. The following code shows how to use this function in practice:
#create and view data frame
df
#sort from least recent to most recent
df[order(as.Date(df$date, format="%m/%d/%Y")),]
date sales
1 10/30/2021 3
3 11/13/2021 14
2 11/18/2021 15
4 11/19/2021 9
#sort from most recent to least recent
df[rev(order(as.Date(df$date, format="%m/%d/%Y"))),]
date sales
4 11/19/2021 9
2 11/18/2021 15
3 11/13/2021 14
1 10/30/2021 3
Method 2: Use lubridate and dplyr
A faster way to sort a data frame by a date variable is to use functions from the lubridate and dplyr packages. The following code shows how to use these functions in practice:
#create and view data frame
df
#sort from least recent to most recent
df %>% arrange(mdy(df$date))
date sales
1 10/30/2021 3
2 11/13/2021 14
3 11/18/2021 15
4 11/19/2021 9
#sort from most recent to least recent
df %>% arrange(desc(mdy(df$date)))
date sales
1 11/19/2021 9
2 11/18/2021 15
3 11/13/2021 14
4 10/30/2021 3
Note that we used lubridate to specify the date as a mdy() format, but you can refer to this cheat sheet to see other date formats if your date happens to be in a different format.
Additional Resources
How to Extract Year from Date in R
How to Aggregate Daily Data to Monthly and Yearly in R
How to Arrange Rows in R