How to Sort a Data Frame by Dates in R (Example Code)
This article shows how to sort a data frame based on a date column in the R programming language.
Creation of Example Data
my_df <- data.frame(date = c("2024/12/03", # Creating some data "2021/07/01", "2022/01/11", "2017/05/03", "2021/11/17"), col1 = 11:15, col2 = LETTERS[1:5]) my_df # Showing example data in RStudio console # date col1 col2 # 1 2024/12/03 11 A # 2 2021/07/01 12 B # 3 2022/01/11 13 C # 4 2017/05/03 14 D # 5 2021/11/17 15 E |
my_df <- data.frame(date = c("2024/12/03", # Creating some data "2021/07/01", "2022/01/11", "2017/05/03", "2021/11/17"), col1 = 11:15, col2 = LETTERS[1:5]) my_df # Showing example data in RStudio console # date col1 col2 # 1 2024/12/03 11 A # 2 2021/07/01 12 B # 3 2022/01/11 13 C # 4 2017/05/03 14 D # 5 2021/11/17 15 E
Example: Apply as.Date() Function to Sort data.frame by Date Variable
my_df$date <- as.Date(my_df$date, # Modify date variable class format = "%Y/%m/%d") |
my_df$date <- as.Date(my_df$date, # Modify date variable class format = "%Y/%m/%d")
my_df <- my_df[order(my_df$date), ] # Sorting data frame by date my_df # Showing ordered data frame in console # date col1 col2 # 4 2017-05-03 14 D # 2 2021-07-01 12 B # 5 2021-11-17 15 E # 3 2022-01-11 13 C # 1 2024-12-03 11 A |
my_df <- my_df[order(my_df$date), ] # Sorting data frame by date my_df # Showing ordered data frame in console # date col1 col2 # 4 2017-05-03 14 D # 2 2021-07-01 12 B # 5 2021-11-17 15 E # 3 2022-01-11 13 C # 1 2024-12-03 11 A
Further Resources
You may find some additional R programming language tutorials on topics such as variables, factors, and dates in the following list: