How to Sort a DataFrame by Date in R?
Last Updated :
19 Dec, 2021
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
data= data.frame (date= c ( '1/1/2021' , '4/5/2021' ,
'2/3/2021' , '11/21/2011' ),
values= c (34,56,78,32))
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
data = data.frame (date= c ( '1/1/2021' , '4/5/2021' ,
'2/3/2021' , '11/21/2011' ),
values= c (34, 56, 78, 32))
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
data = data.frame (date= c ( '1/1/2021' , '4/5/2021' ,
'2/3/2021' , '11/21/2011' ),
values= c (34, 56, 78, 32))
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
library (lubridate)
library (dplyr)
data = data.frame (date= c ( '1/1/2021' , '4/5/2021' ,
'2/3/2021' , '11/21/2011' ),
values= c (34, 56, 78, 32))
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
library (lubridate)
library (dplyr)
data = data.frame (date= c ( '1/1/2021' , '4/5/2021' ,
'2/3/2021' , '11/21/2011' ),
values= c (34, 56, 78, 32))
data % > % arrange ( desc ( mdy (data$date)))
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...