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:
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: