I have a data frame DF with one of the columns being date/Time and I would like to order the data frame in descending order of this column.
DF <- data.frame(ID=c('ID3', 'ID2','ID1'), end=c('4/1/10 12:00', '6/1/11 14:20', '1/1/09 11:10'), age=c(40,30,20));
I first converted the end
column into et
using et = as.POSIXct(DF$end,format='%m/%d/%Y %H:%M')
, and used the following, but got the error that unary operator '-' is not accepted for the argument :
out <- DF[order(-DF$et),];
I also tried used the descending flag but again got an error about arguments not being of same length.
out <- DF[order(DF$et, descending=TRUE),];
However, the ascending order seems to work: out <- DF[order(DF$et),]
.
How can I order in descending order (most recent time first)? Thank you.
Sorting Data To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.
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.
The most basic way to sort a data frame by a date variable in R is to use the order() function from base R.
Use the sort() function to sort vector elements in R by ascending or descending order. This sort() function takes an R vector as an argument and results in the sorted vector by default in ascending order. Use decreasing=TRUE param to sort vectors in descending order.
There is an easy and general solution for your issue with few code.
As you have noticed, the minus sign doesn't work with Dates because negative dates don't yet exist!
However you can have the same effect with a general purpose function: rev(). Therefore, you mix rev and order like:
#init data
DF <- data.frame(ID=c('ID3', 'ID2','ID1'), end=c('4/1/10 12:00', '6/1/11 14:20', '1/1/09 11:10')
#change order
out <- DF[rev(order(as.Date(DF$end))),]
When you use the minus sign with numbers you are classing negative numbers in one pass. I think that when you use rev() function, you are doing two passes, one to sort in ascending order and one for reversing the order. But on 3 observations, it's hard to see.
Hope it helped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With