How to Sort a DataFrame by Date in R?
In this article, we will discuss how to sort a dataframe in R Programming Language.
We can create a dataframe in R by using data.frame() function. In a dataframe we can create a date column using as.Date() function in the ‘%m/%d/%Y’ format.
Example:
Let’s create a dataframe with 2 columns including dates
R
# create a dataframe data= data.frame (date= c ( '1/1/2021' , '4/5/2021' , '2/3/2021' , '11/21/2011' ), values= c (34,56,78,32)) # display data |
Output:
Method 1: User order() from base 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.
Syntax:
data[order(as.Date(data$column_name, format="%m/%d/%Y")),]
where
- data is the input dataframe
- column_name is the date column
Example:
R
# create a dataframe data = data.frame (date= c ( '1/1/2021' , '4/5/2021' , '2/3/2021' , '11/21/2011' ), values= c (34, 56, 78, 32)) # display data[ order ( as.Date (data$date, format= "%m/%d/%Y" )), ] |
Output:
In order to sort in descending order, we have to use rev() function which is used to reverse the dataframe
Example:
R
# create a dataframe data = data.frame (date= c ( '1/1/2021' , '4/5/2021' , '2/3/2021' , '11/21/2011' ), values= c (34, 56, 78, 32)) # display data[ rev ( order ( as.Date (data$date, format= "%m/%d/%Y" ))), ] |
Output:
Method 2: Use functions from the lubridate and dplyr packages
We can use these packages to sort the dataframe by date using the below methods. mdy() is used to sort the date in the dataframe and will sort it in ascending order
Syntax:
data %>% arrange(mdy(data$column_name))
where
- data is the input dataframe
- column_name is the date column
Example:
R
# import libraries library (lubridate) library (dplyr) # create a dataframe data = data.frame (date= c ( '1/1/2021' , '4/5/2021' , '2/3/2021' , '11/21/2011' ), values= c (34, 56, 78, 32)) # display data % > % arrange ( mdy (data$date)) |
Output:
If we want to sort the date in the dataframe in reverse order, then we have to use desc() function
Syntax:
data %>% arrange(desc(mdy(data$column_name)))
Example:
R
# import libraries library (lubridate) library (dplyr) # create a dataframe data = data.frame (date= c ( '1/1/2021' , '4/5/2021' , '2/3/2021' , '11/21/2011' ), values= c (34, 56, 78, 32)) # display data % > % arrange ( desc ( mdy (data$date))) |
Output: