Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering date/time in descending order in R

Tags:

date

r

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.

like image 835
user2327621 Avatar asked May 05 '13 21:05

user2327621


People also ask

How do I order in descending order in R?

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.

How do you arrange dates in ascending order in 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.

How do I sort a date variable in R?

The most basic way to sort a data frame by a date variable in R is to use the order() function from base R.

How do I sort a vector of dates in 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.


1 Answers

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.

like image 89
pommedeterresautee Avatar answered Nov 12 '22 15:11

pommedeterresautee